POJ3070Fibonacci
题意&思路:
求斐波那契数列的第n项
f
n
%
10000
f_n\%10000
fn%10000。
矩阵快速幂模板题,题目已经告诉你了矩阵怎么求。
代码:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<algorithm>
#include<string.h>
#include<ctype.h>
#include<queue>
#include<set>
#include<stack>
#include<cmath>
#include<map>
#define pii pair<int,int>
#define ll long long
#define cl(x,y) memset(x,y,sizeof(x))
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
const int N=1e6+10;
const int mod=1e4;
const int maxn=0x3f3f3f3f;
const int minn=0xc0c0c0c0;
const int inf=99999999;
using namespace std;
struct node
{
int maze[5][5];
node()
{
cl(maze,0);
}
};
node mul(node a,node b)
{
node c;
int i,j,k;
for(i=1;i<=2;i++)
for(j=1;j<=2;j++)
for(k=1;k<=2;k++)
c.maze[i][j]=(c.maze[i][j]+a.maze[i][k]*b.maze[k][j])%mod;
return c;
}
node matpow(node a,int n)
{
node b;
int i,j;
for(i=1;i<=2;i++)
for(j=1;j<=2;j++)
b.maze[i][j]=i==j?1:0;
while(n)
{
if(n&1)
b=mul(b,a);
a=mul(a,a);
n>>=1;
}
return b;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n;
while(cin>>n && n!=-1)
{
node a;
a.maze[1][1]=1;
a.maze[1][2]=1;
a.maze[2][1]=1;
a=matpow(a,n);
cout<<a.maze[1][2]<<endl;
}
return 0;
}