hdu2802之矩阵乘法

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
  
  
1 2 3 0
 

Sample Output
  
  
1 7 20
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using 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;
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值