您的位置:首页 > 其它

codeforces 185A Plant

2013-08-23 21:09 369 查看
点击打开cf 185A

思路: 递推+矩阵快速幂

分析:

1 题目要求找到在n年后向上三角形的个数

2 写出前面的几个数F(0) = 1 , F(1) = 3 , F(2) = 10 , F(3) = 36 , F(4) = 136

   通过前面几项我们可以找到通项公式F
= 4*F[n-1]-2^(n-1)

     那么我们通过够找矩阵

   | 4 -1 |  *  | F(n-1) | = | F(n) |

   | 0 2 |      | 2^(n-1) |   | 2^n |

3 那么够造出矩阵之后我们直接利用矩阵快速幂,由于矩阵开始有负数,所以应该在取模的时候注意一下

代码:

/************************************************
* By: chenguolin                               *
* Date: 2013-08-23                             *
* Address: http://blog.csdn.net/chenguolinblog *
***********************************************/
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;

typedef __int64 int64;
const int MOD = 1e9+7;
const int N = 2;

int64 n;
struct Matrix{
int64 mat

;
Matrix operator*(const Matrix& m)const{
Matrix tmp;
for(int i = 0 ; i < N ; i++){
for(int j = 0 ; j < N ; j++){
tmp.mat[i][j] = 0;
for(int k = 0 ; k < N ; k++){
tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD;
tmp.mat[i][j] %= MOD;
}
}
}
return tmp;
}
};

int64 Pow(Matrix &m){
if(n == 0)
return 1;
Matrix ans;
ans.mat[0][0] = 1 , ans.mat[0][1] = 0;
ans.mat[1][0] = 0 , ans.mat[1][1] = 1;
while(n){
if(n%2)
ans = ans*m;
n /= 2;
m = m*m;
}
int64 sum = 0;
sum = (ans.mat[0][0]+ans.mat[0][1])%MOD;
sum = (sum+MOD)%MOD;
return sum;
}

int main(){
Matrix m;
while(cin>>n){
m.mat[0][0] = 4 , m.mat[0][1] = -1;
m.mat[1][0] = 0 , m.mat[1][1] = 2;
cout<<Pow(m)<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: