码迷,mamicode.com
首页 > 其他好文 > 详细

poj - 3070 题解

时间:2017-08-22 16:07:22      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:ret   main   cst   解决   names   pow   space   斐波那契数   std   

题意:斐波那契数列的矩阵链乘求法。

题解:快速幂优化矩阵链乘解决。

 

 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 }

 

poj - 3070 题解

标签:ret   main   cst   解决   names   pow   space   斐波那契数   std   

原文地址:http://www.cnblogs.com/shao0099876/p/7411644.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!