poj3070 Fibonacci 矩阵的幂

http://poj.org/problem?id=3070

转载链接:https://blog.csdn.net/yu121380/article/details/79900385

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int MOD=10000;
struct mat{
	long long a[2][2];
};
mat mat_mul(mat x,mat y){
	mat res;
	memset(res.a,0,sizeof(res.a));
	for(int i=0;i<2;i++){
		for(int j=0;j<2;j++){
			for(int k=0;k<2;k++){
				res.a[i][j]=(res.a[i][j]+x.a[i][k]*y.a[k][j])%MOD;
			}
		}
	}
	return res;
}
void mat_pow(int n){
	mat c,res;
	c.a[0][0]=c.a[0][1]=c.a[1][0]=1;
	c.a[1][1]=0;
	memset(res.a,0,sizeof(res.a));
	res.a[0][0]=1;
	while(n){
		if(n&1){
			res=mat_mul(res,c);	
		}
		c=mat_mul(c,c);
		n=n>>1;
	}
	cout<<res.a[0][1]<<endl;
	/*for(int i=0;i<2;i++){
		for(int j=0;j<2;j++){
			cout<<res.a[i][j]<<' ';
		}
		cout<<endl;
	}*/
}
int main(){
	int n;
	while(cin>>n)
	{
		if(n==-1) break;
		else mat_pow(n);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/skykone1/article/details/87903105