Codeforces Round #113 (Div. 2) Tetrahedron(滚动DP)

时间:2024-01-16 11:12:50
Tetrahedron
time limit per test

2 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

You are given a tetrahedron. Let's mark its vertices with letters ABC and D correspondingly.

Codeforces Round #113 (Div. 2) 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 Dto 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
Note

The required paths in the first sample are:

  • D - A - D
  • D - B - D
  • D - C - D

【题意】给你一个四面体,每一个顶点可以走一步到达他相邻的顶点,每一步必须走,不能停留在原地。问你从D点出发经过n步再回到

D点的方案数是多少。

【分析】简单DP,dp[i][j]表示第j步走到顶点i的方案数,然后用其他三个顶点更新就行了。但是...会MLE。我们发现每一种状态只与他前一步的状态有关,之前的没用了,空间浪费,所以可以考虑用滚动数组。

#include <bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define vi vector<int>
#define inf 0x3f3f3f3f
#define met(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long LL;
const int N = 1e7+;
const int mod = 1e9+;
int n;
LL dp[][];
int main(){
scanf("%d",&n);
dp[][]=dp[][]=dp[][]=;
for(int i=;i<=n;i++){
int k=i&;
dp[][k]=(dp[][k^]+dp[][k^]+dp[][k^])%mod;
dp[][k]=(dp[][k^]+dp[][k^]+dp[][k^])%mod;
dp[][k]=(dp[][k^]+dp[][k^]+dp[][k^])%mod;
dp[][k]=(dp[][k^]+dp[][k^]+dp[][k^])%mod;
}
printf("%lld\n",dp[][n&]);
return ;
}