codeforces 185A. Plant


​http://codeforces.com/problemset/problem/185/A​


codeforces 185A. Plant(规律)_#include

问经过N年后,向上的三角形的个数。

第一种解法:矩阵递推可以发现一年后,新的三角形图形含有的三角形的个数是上一三角形图形含有的三角形个数的4倍。不过中间的那一块上下方向转变了。由此我们可以得到递推式:设f[n][0]是第N年后的图形的上三角形个数,f[n][1]是第N年后图形的下三角形个数。

codeforces 185A. Plant(规律)_递推_02

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
struct matrix{
LL m[2][2];
};
matrix I={
1,0,
0,1
};
matrix A={
3,1,
1,3
};
matrix multi(matrix a,matrix b){
matrix c;
for(int i=0;i<2;i++){
for(int j=0;j<2;j++){
c.m[i][j]=0;
for(int k=0;k<2;k++){
c.m[i][j]=c.m[i][j]+a.m[i][k]*b.m[k][j]%mod;
}
c.m[i][j]%=mod;
}
}
return c;
}
matrix power(LL p){
matrix ans=I,temp=A;
while(p){
if(p&1) ans=multi(ans,temp);
temp=multi(temp,temp);
p>>=1;
}
return ans;
}
int main()
{
LL n;
while(cin>>n){
matrix ans=power(n);
printf("%I64d\n",ans.m[0][0]);
}
return 0;
}


第二种解法:斜着右上方查看每一列的上三角形的数量变化。嘿嘿,规律出现了。

codeforces 185A. Plant(规律)_规律_03

#include <iostream>
#include <cstdio>
using namespace std;
typedef long long LL;
const LL mod=1e9+7;
LL power(LL p){
LL ans=1,temp=2;
while(p){
if(p&1) ans=ans*temp%mod;
temp=temp*temp%mod;
p>>=1;
}
return ans;
}
int main()
{
LL n;
while(cin>>n){
if(n==0){
puts("1");
continue;
}
printf("%I64d\n",(power(2*n-1)+power(n-1))%mod);
}
return 0;
}