真是神奇的斐波那契有这样的矩阵关系
f[0]=0;f[1]=1;f[2]=1;f[3]=2......
初始为单位矩阵即可;
题目链接:http://poj.org/problem?id=3070
#include<cstdio>
#include<cstring>
using namespace std;
const int mod=10000;
struct node
{
int map[2][2];
}q,c;
void init(node &a)
{
a.map[0][0]=a.map[1][1]=1;
a.map[0][1]=a.map[1][0]=0;
c.map[0][0]=c.map[0][1]=c.map[1][0]=1;
c.map[1][1]=0;
}
node mul(node a,node b)
{
int i,j,k;
node c;
memset(c.map,0,sizeof(c.map));
for(i=0;i<2;i++)
for(j=0;j<2;j++)
for(k=0;k<2;k++)
c.map[i][j]=(c.map[i][j]+(a.map[i][k]*b.map[k][j]))%mod;
return c;
}
int main()
{
int k;
while(scanf("%d",&k)!=EOF)
{
if(k==-1)
break;
init(q);
while(k>0)
{
if(k&1)
q=mul(q,c);
c=mul(c,c);
k=k/2;
}
printf("%d\n",q.map[0][1]);
}
return 0;
}
题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=1005
思路:只在相乘的矩阵中稍作修改即可
注意:此题的初始状态不可直接设置为单位矩阵,所以在代码中做了特判
#include<cstdio>
#include<cstring>
using namespace std;
const int mod=7;
struct node
{
int map[2][2];
}q,c;
void init(int a,int b)
{
q.map[0][0]=a+b;
q.map[1][1]=1;
q.map[0][1]=1;
q.map[1][0]=1;
c.map[0][0]=a;
c.map[0][1]=1;
c.map[1][0]=b;
c.map[1][1]=0;
}
node mul(node a,node b)
{
int i,j,k;
node c;
memset(c.map,0,sizeof(c.map));
for(i=0;i<2;i++)
for(j=0;j<2;j++)
for(k=0;k<2;k++)
c.map[i][j]=(c.map[i][j]+(a.map[i][k]*b.map[k][j]))%mod;
return c;
}
int main()
{
int a,b,k;
while(scanf("%d%d%d",&a,&b,&k)!=EOF)
{
if(a==0&&b==0&&k==0)
break;
if(k<3)
{
printf("1\n");
continue;
}
else if(k==3)
{
printf("%d\n",a+b);
continue;
}
else
{
k-=2;
init(a,b);
while(k>0)
{
if(k&1)
q=mul(q,c);
c=mul(c,c);
k=k/2;
}
printf("%d\n",q.map[0][1]);
}
}
return 0;
}