CF 185A(递推式构造矩阵求解)

来源:互联网 发布:淘宝主图背景素材psd 编辑:程序博客网 时间:2024/05/16 14:14
A. Plant
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Dwarfs have planted a very interesting plant, which is a triangle directed "upwards". This plant has an amusing feature. After one year a triangle plant directed "upwards" divides into four triangle plants: three of them will point "upwards" and one will point "downwards". After another year, each triangle plant divides into four triangle plants: three of them will be directed in the same direction as the parent plant, and one of them will be directed in the opposite direction. Then each year the process repeats. The figure below illustrates this process.

Help the dwarfs find out how many triangle plants that point "upwards" will be in n years.

Input

The first line contains a single integer n (0 ≤ n ≤ 1018) — the number of full years when the plant grew.

Please do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use cincout streams or the %I64d specifier.

Output

Print a single integer — the remainder of dividing the number of plants that will point "upwards" in n years by 1000000007 (109 + 7).

Examples
input
1
output
3
input
2
output
10
Note

The first test sample corresponds to the second triangle on the figure in the statement. The second test sample corresponds to the third one.

思路:

找规律得递推式为:F(n) = 4*F(n-1) - 2^(n-1)

有递推式构造快速幂矩阵 : 4   -1

    0    2

代码:

#include <cstdio>#include <cstdlib>#include <algorithm>#include <cmath>#include <cstring>using namespace std;typedef long long int ll;const ll mod = 1e9+7;struct matrix{ll a[2][2];matrix operator*(const matrix& tmp){matrix ans;for(int i=0; i<2; i++)for(int j=0; j<2; j++){ans.a[i][j] = 0;for(int k=0; k<2; k++)ans.a[i][j] = (ans.a[i][j] + ((a[i][k]*tmp.a[k][j])%mod) )%mod;}return ans;}};matrix quick_pow(matrix a,ll n){matrix ans;ans.a[0][0] = ans.a[1][1] = 1;ans.a[0][1] = ans.a[1][0] = 0;while(n){if(n%2)ans = ans*a;a = a*a;n /= 2;}return ans;}int main(){ll N;scanf("%I64d",&N);if(N==0){printf("1\n");return 0;}matrix m;m.a[0][0] = 4;m.a[0][1] = -1;m.a[1][0] = 0;m.a[1][1] = 2;m = quick_pow(m,N-1);ll ans = (m.a[0][0]*3 + m.a[0][1]*2)%mod + mod;printf("%I64d\n",ans%mod);return 0;}

0 0
原创粉丝点击