poj - 3070 题解

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

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

 

 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 }

 

转载于:https://www.cnblogs.com/shao0099876/p/7411644.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值