codeforces 185A Plant(矩阵快速幂)

来源:互联网 发布:路由器防蹭网屏蔽软件 编辑:程序博客网 时间:2024/05/21 22:36

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 %I64dspecifier.

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.





题意:

一个三角形,在内部分为4个三角形,那么有3个是朝上的,1个是朝下的,且每年分一次,问第n年有多少个朝上的三角形。


思路:

我们用up[i], down[i] 表示第i年朝上的有up[i]个,朝下的有down[i]个,那么我们很容易推出:

up[i] = up[i-1]*3 + down[i]*1;

down[i] = down[i-1]*3 + up[i]*1;

于是,构造矩阵发现,

【1】【3】

【3】【1】这个矩阵的n次方中包含了up[n]和down[n]的信息,只需特判一下n的奇偶性,就可以求出。


总结:

这题看了题后,很快就有了思路,敲出了代码,然后发现测试样例都没过,检查代码发现矩阵乘法部分下标习惯性全部写成了i和j,改好后交WA,发现了没有模,改了继续交,任然WA,后面学长提醒数据范围,改了long long, MLE,最裸的矩阵快速幂居然MLE,想想就不科学。后面发现改的次数多了,有的地方改着改着就忘了,参数的传递类型竟然不匹配,改了继续WA,后面发现结构体mat里的int没改,改了发现任然MLE。学长又提醒数据范围了,终于发现下限没有特判n=0,AC了唯一一题。。本来开场一个小时不到就有思路的题,写到了结束前40分钟。。


代码:

#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>using namespace std;typedef long long LL;const LL M = 1000000007;struct mat{LL tu[2][2];mat(){memset(tu, 0, sizeof(tu));}};mat base;mat operator*(const mat &a, const mat &b){mat c;for(int i=0; i<2; i++)for(int j=0; j<2; j++)for(int k=0; k<2; k++)c.tu[i][j] = (c.tu[i][j]+a.tu[i][k]*b.tu[k][j])%M;return c;}mat fastMul(LL k){if(k==1)return base;if(k%2!=0)return base*fastMul(k-1);else{mat tmp = fastMul(k/2);return tmp*tmp;}}void sol(LL n){mat ans = fastMul(n);if(n%2==0)        cout<<ans.tu[0][0]<<endl;    else        cout<<ans.tu[0][1]<<endl;}int main(){LL n;while(cin>>n){        if(n==0) {cout<<1<<endl; continue;} //特判,n可能为0base.tu[0][0] = 1; base.tu[0][1] = 3;base.tu[1][0] = 3; base.tu[1][1] = 1;sol(n);}return 0;}


0 0
原创粉丝点击