POJ 3070 矩阵乘法 模板

题意:

求斐波那契数列第n项,mod 10000

思路:

本来是需要自己构造矩阵的,可是这题太仁慈了,都给画出来了,不愧是模板题~

 

贡献我丑陋的模板

PS:还是要反对模板化的代码,还是亲手打才是最好的,我都是现打的,不过需者自取~

 

View Code
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdlib>
 4 #include <cstdio>
 5 
 6 #define SIZE 4 
 7 #define mod 10000
 8 
 9 using namespace std;
10 
11 struct MATRIX
12 {
13     int mt[SIZE][SIZE];
14     int x,y;
15 }ans,def;
16 
17 int n;
18 
19 inline MATRIX operator *(MATRIX a,MATRIX b)
20 {
21     MATRIX c;
22     memset(c.mt,0,sizeof c.mt);
23     c.x=a.x; c.y=b.y;
24     for(int i=1;i<=a.x;i++)
25         for(int j=1;j<=b.y;j++)
26             for(int k=1;k<=a.y;k++)
27                 c.mt[i][j]=(c.mt[i][j]+(a.mt[i][k]%mod)*(b.mt[k][j]%mod))%mod;
28     return c;
29 }
30 
31 inline MATRIX operator +(MATRIX a,MATRIX b)
32 {
33     MATRIX c;
34     memset(c.mt,0,sizeof c.mt);
35     c.x=a.x; c.y=a.y;
36     for(int i=1;i<=c.x;i++)
37         for(int j=1;j<=c.y;j++)
38             c.mt[i][j]=(a.mt[i][j]+b.mt[i][j])%mod;
39     return c;
40 }
41 
42 inline bool prt(MATRIX &c)
43 {
44     for(int i=1;i<=c.x;i++)
45     {
46         for(int j=1;j<=c.y;j++) printf("%d ",c.mt[i][j]);
47         puts("");
48     }
49 }
50 
51 void go()
52 {
53     n-=2;
54     def.mt[1][1]=def.mt[1][2]=def.mt[2][1]=1;
55     def.mt[2][2]=0; def.x=def.y=2;
56     ans.mt[1][1]=ans.mt[1][2]=ans.mt[2][1]=1; ans.mt[2][2]=0;
57     ans.x=ans.y=2;
58     
59     while(n)
60     {
61         if(n&1) ans=ans*def;
62         def=def*def;
63         n>>=1;
64     }
65     printf("%d\n",ans.mt[1][1]);
66 }
67 
68 int main()
69 {
70     while(scanf("%d",&n))
71     {
72         if(n==-1) break;
73         else if(n==0) puts("0");
74         else if(n==1) puts("1");
75         else go();
76     }
77     system("pause");
78     return 0;
79 }

 

 

posted @ 2012-10-10 19:52  proverbs  阅读(616)  评论(0编辑  收藏  举报