hdu2802之矩阵乘法

来源:互联网 发布:谢云流小时候捏脸数据 编辑:程序博客网 时间:2024/06/05 11:09

F(N)

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2537    Accepted Submission(s): 840


Problem Description

Giving the N, can you tell me the answer of F(N)?
 

Input
Each test case contains a single integer N(1<=N<=10^9). The input is terminated by a set starting with N = 0. This set should not be processed.
 

Output
For each test case, output on a line the value of the F(N)%2009.
 

Sample Input
1230
 

Sample Output
1720
#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<map>#include<iomanip>#define INF 99999999using namespace std;const int MAX=5;const int mod=2009;int array[MAX][MAX],sum[MAX][MAX];void MatrixMult(int a[MAX][MAX],int b[MAX][MAX]){int c[MAX][MAX]={0};for(int i=0;i<MAX;++i){for(int j=0;j<MAX;++j){for(int k=0;k<MAX;++k){c[i][j]+=a[i][k]*b[k][j];}}}for(int i=0;i<MAX;++i){for(int j=0;j<MAX;++j)a[i][j]=c[i][j]%mod;}}int MatrixPow(int k){for(int i=0;i<MAX;++i){for(int j=0;j<MAX;++j)sum[i][j]=(i == j);}array[0][0]=0,array[0][1]=array[0][4]=1,array[0][2]=3,array[0][3]=-3;array[1][0]=1,array[1][1]=array[1][2]=array[1][3]=array[1][4]=0;array[2][0]=array[2][1]=0,array[2][2]=array[2][4]=1,array[2][3]=2;array[3][0]=array[3][1]=array[3][2]=0,array[3][3]=array[3][4]=1;array[4][0]=array[4][1]=array[4][2]=array[4][3]=0,array[4][4]=1;while(k){if(k&1)MatrixMult(sum,array);MatrixMult(array,array);k>>=1;}return (sum[0][0]*7+sum[0][1]+sum[0][2]*9+sum[0][3]*3+sum[0][4])%mod;}int main(){int n;while(scanf("%d",&n),n){if(n == 1)printf("1\n");if(n == 2)printf("7\n");if(n>2)printf("%d\n",MatrixPow(n-2));}return 0;} 

原创粉丝点击