Tetrahedron(dp)

You are given a tetrahedron. Let’s mark its vertices with letters A, B, C and D correspondingly.
Tetrahedron(dp)

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).

Examples
Input
2
Output
3
Input
4
Output
21
题目分析:
说真的,看到这题真的是又开心又难过,开心的是只要推出公式来就完事了,难过的是这公式不好推啊。
看了别人的题解才明白。我们把ABCD分别用0123对应,设dp[i][k]为走i步到达k所对应的那个点所需的最小步数。
那么dp[i][j]=dp[i][j]+dp[i-1][k]
代码:

#include<iostream>
using namespace std;
const int max_n=1e7+10;
const int mod=1e9+7;
int dp[max_n][4];
int main()
{
    dp[1][0]=1;
    dp[1][1]=1;
    dp[1][2]=1;
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
        for(int j=0;j<=3;j++)
        for(int k=0;k<=3;k++)
    {
        if(k!=j) {
            dp[i][j]+=dp[i-1][k];
            dp[i][j]%=mod;
        }
    }
    cout<<dp[n][3];
    return 0;
}
Tetrahedron(dp)Tetrahedron(dp) ナナ色のブランク 发布了36 篇原创文章 · 获赞 30 · 访问量 8876 私信 关注
上一篇:06-图1 列出连通集 (25 分)


下一篇:前端小白的数据结构学习总结——图