9558. Flags
The flag consists of n vertical stripes, each of which can be colored white, red, or
blue. Moreover:
·
No two
adjacent stripes may have the same color.
·
Any
blue stripe must be placed between a red and a white stripe (in any order).
How many ways are there to color a flag
with n stripes?
Input. One integer n (1 ≤ n ≤ 106)
– the number of stripes on the
flag.
Output. Print the number of ways to color a flag
with n stripes. The answer should be given modulo 109 + 7.
|
Sample
input |
Sample
output |
|
3 |
4 |
Fibonacci numbers
Let:
·
fr(n) be the number of ways to color a
flag with n
stripes, starting with a red stripe;
·
fw(n) be the number of ways to color a
flag with n
stripes, starting with a white stripe.
Let’s consider how to compute the function fr(n):
·
If the
stripe following the red one is white, then the remaining flag of length n – 1 can be colored in fw(n – 1) ways;
·
If the
stripe following the red one is blue, then the stripe after the blue one must
be white. After that, the remaining flag of length n – 2 can be colored in fw(n – 2) ways;
Thus, we obtain the following equality:
fr(n) = fw(n – 1) + fw(n
– 2)
By analogous reasoning, we obtain:
fw(n) = fr(n – 1) + fr(n – 2)
The initial conditions for the first
recurrence are obvious:
·
fr(1) = 1: A flag consisting of one stripe and
starting with red can be colored in exactly one way – R.
·
fr(2) = 1: If the first stripe is red, then the second stripe cannot be red and
cannot be blue (since a blue stripe must be placed between a red and a white
stripe). Therefore, the second stripe must be white. The only possible
arrangement is RW.
Similarly,
fw(1) = 1, fw(2) = 1
Both functions fr(n) and fw(n) define
Fibonacci numbers:
fr(n) = Fn,
fw(n) = Fn
The coloring of the flag starts with the
first stripe. It can be either red or white. Therefore, the total number of
ways to color the flag is
fr(n) + fw(n) = 2 * Fn
Declare the constants.
#define MAX 1000001
#define MOD 1000000007
Declare an array fib to store the Fibonacci numbers.
long long fib[MAX];
Read the input
value n.
scanf("%d", &n);
Fill the array fib with Fibonacci numbers.
fib[1] = 1; fib[2] = 1;
for (i = 3; i < MAX; i++)
fib[i] = (fib[i - 1] + fib[i - 2]) % MOD;
Print the answer.
printf("%lld\n", (2 * fib[n]) % MOD);