You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.
![](https://i-blog.csdnimg.cn/blog_migrate/f7885d26e8d195c16528a7edc920691a.png)
An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.
You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertexD to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
2
3
4
21
The required paths in the first sample are:
- D - A - D
- D - B - D
- D - C - D
解题说明:此题可以算是一道DP问题,从椎体的顶部D出发,指定走n步,要求最后回到D即可。假设走i步回到起点的走法数为f[i],那么可以得到
f[i]=f[i-1]*2+f[i-2]*3
这个公式的意思是说,在i-1步能走到起点的所有行走路线中,我们调整最后两步,让倒数第2步走到除当前点和起点外的另外两个点,最后一步再走到起点,所以选择是f[i-1]*2. 至于i-2步,依旧是考虑最后两个步骤,倒数第2步没有什么要求,选择有3种。有了这个公式,最后打表即可。
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
unsigned int n;
int i;
long long f[10000001];
f[1] = 0;
f[2] = 3;
f[3] = 6;
for(i=4; i<10000001;i++)
{
f[i] = f[i-1] * 2 + f[i-2] * 3;
f[i] %= 1000000007;
}
scanf("%d", &n);
cout<<f[n]<<endl;
return 0;
}