http://codeforces.com/problemset/problem/185/A
CodeForces - 185A Plant
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 cin, cout 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).
Sample test(s)
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.
题意
求第n个图形中,上三角形的个数?
思路
找到递推关系式:
构造矩阵:
AC Code
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const ll nmax=2;
const ll MOD=1e9+7;
#define mod(x) ((x)%MOD)
struct mat{
ll m[nmax][nmax];
}unit;
//A*B^(n-2)=C //C矩阵的首项即为f(n)
mat operator *(mat a,mat b){
mat ret;
ll x;
for(ll i=0;i<nmax;i++){//3*3
for(int j=0;j<nmax;j++){
x=0;
for(ll k=0;k<nmax;k++){
x+=mod((ll)a.m[i][k]*b.m[k][j]);
}
ret.m[i][j]=mod(x);
}
}
return ret;
}
void init_unit(){
for(ll i=0;i<nmax;i++){
unit.m[i][i]=1;
}
return;
}
mat pow_mat(mat a,ll n){//求矩阵a的n次幂
mat ret=unit;
while(n){
if(n&1) ret=ret*a;
a=a*a;
n>>=1;
}
return ret;
}
ll quick_pow(ll a,ll n){//求数a的n次幂
ll ans=1;
while(n){
if(n&1) ans=(ans*a)%MOD;
a=(a*a)%MOD;
n>>=1;
}
return ans;
}
int main(int argc, char** argv) {
ll n;
init_unit();
while(scanf("%lld",&n)!=EOF){
if(n==0) printf("1\n");
else if(n==1) printf("3\n");
else{
mat a,b;
b.m[0][0]=3;b.m[0][1]=1;
b.m[1][0]=1;b.m[1][1]=3;
a.m[0][0]=3;a.m[0][1]=1;
b=pow_mat(b,n-1);
a=a*b;
printf("%lld\n",a.m[0][0]);
}
}
return 0;
}