题意:斐波那契数列的矩阵链乘求法。
题解:快速幂优化矩阵链乘解决。
1 #include<iostream>
2 #include<algorithm>
3 #include<cstdio>
4 #include<cstring>
5 using namespace std;
6 struct datatype
7 {
8 int a[2][2];
9 };
10 datatype multiple(datatype x,datatype y)
11 {
12 datatype res;
13 memset(res.a,0,sizeof(res.a));
14 for(int i=0;i<=1;i++)
15 {
16 for(int j=0;j<=1;j++)
17 {
18 for(int k=0;k<=1;k++)
19 {
20 res.a[i][j]+=x.a[i][k]*y.a[k][j];
21 }
22 }
23 }
24 for(int i=0;i<=1;i++)
25 {
26 for(int j=0;j<=1;j++)
27 {
28 res.a[i][j]%=10000;
29 }
30 }
31 return res;
32 }
33 datatype power(datatype x,int y)
34 {
35 datatype res,t;
36 res.a[0][0]=1;
37 res.a[0][1]=0;
38 res.a[1][0]=0;
39 res.a[1][1]=1;
40 t=x;
41 while(y)
42 {
43 if(y&1)
44 {
45 res=multiple(res,t);
46 }
47 t=multiple(t,t);
48 y>>=1;
49 }
50 return res;
51 }
52 int main()
53 {
54 int n;
55 while(true)
56 {
57 scanf("%d",&n);
58 if(n==-1)
59 {
60 break;
61 }
62 datatype t;
63 t.a[0][0]=1;
64 t.a[0][1]=1;
65 t.a[1][0]=1;
66 t.a[1][1]=0;
67 if(n==0)
68 {
69 printf("0\n");
70 continue;
71 }
72 t=power(t,n);
73 printf("%d\n",t.a[1][0]%10000);
74 }
75 return 0;
76 }