这是本人写的第一次博客,学了半年的基础C语言,初学算法,若有错误还请指正。
E. Tetrahedron
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly.

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 vertex D 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).
Input
The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.
Output
Print the only integer — the required number of ways modulo 1000000007 (109 + 7).
Sample test(s)
input
2
output
3
input
4
output
21
Note
The required paths in the first sample are:
D - A - D
D - B - D
D - C - D







#include <cstdio>
#include <cstring>
const int N = 1e7 + ;
const int mod = 1e9 + ;
long long dp[N], n;
void init(){
dp[] = ;
dp[] = ;
for(int i = ; i < N; i ++){
dp[i] = * dp[i - ] + * dp[i - ];
dp[i] %= mod;
}
}
int main(){
init();
while(scanf("%d", &n) == )
printf("%d\n", dp[n]);
return ;
}
不过刚开始这点思路非常复杂,所有笔者就去想dp[n] = 2 * dp[n - 1] + 3 *dp[n - 2]的含义
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int mod = 1e9 + ;
int n;
long long a, b;
int main(){
while(scanf("%d", &n) == ){
if(n < )
printf("0\n");
else if(n == )
printf("3\n");
else{
a = ;
b = ;
for(int i = ; i <= n - ; i ++){
if(i & )
a = ( * a + * b)%mod;
else
b = ( * b + * a)%mod;
}
if(n & )
printf("%I64d\n", a);
else
printf("%I64d\n", b);
}
}
return ;
}
#include <cstdio>
#include <cstring>
typedef long long lld;
const int N = 1e7 + ;
const int mod = 1e9 + ;
int dp[N][], n;
void init(){
dp[][] = ;
dp[][] = ;
dp[][] = ;
for(int i = ; i < N; i ++){
for(int j = ; j < ; j ++){
for(int k = ; k < ; k ++){
if(k == j )
continue;
dp[i][j] += dp[i - ][k];
dp[i][j] %= mod;
}
}
}
}
int main(){
init();
while(scanf("%d", &n) == )
printf("%d\n", dp[n][]);
return ;
}
其实可以从这个递推关系式可以推出dp[n] = 2 * dp[n - 1] + 3 *dp[n - 2]

#include <cstdio>
#include <cstring>
const int N = 1e7 + ;
const int mod = 1e9 + ;
long long dp[N], n;
void init(){
dp[] = ;
dp[] = ;
for(int i = ; i < N; i ++){
if(i & )
dp[i] = * dp[i - ] - ;
else
dp[i] = * dp[i - ] + ;
dp[i] %= mod;
}
}
int main(){
init();
while(scanf("%d", &n) == )
printf("%d\n", dp[n]);
return ;
}