您的位置:首页 > 其它

矩阵的连乘

2014-07-28 11:30 106 查看
B - 矩阵快速幂Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64uSubmit StatusDescriptionJzzhu has invented a kind of sequences, they meet the following property:You are given x and y, please calculate fn modulo 1000000007(109 + 7).InputThe first line contains two integers x and y(|x|, |y| ≤ 109).The second line contains a single integer n(1 ≤ n ≤ 2·109).OutputOutput a single integer representing fn modulo 1000000007(109 + 7).Sample InputInput
2 33
Output
1
Input
0 -12
Output
1000000006
HintIn the first sample, f2 = f1 + f3, 3 = 2 + f3, f3 = 1.In the second sample, f2 =  - 1;  - 1 modulo (109 + 7) equals (109 + 6).可以找规律~~~~
#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>using namespace std;typedef long long int LL;const LL mod=1000000007LL;LL a,b,n;int main(){cin>>a>>b>>n;n--;n=n%6;LL ans=0;switch(n){case(0):{ans=(a+mod)%mod;break;}case(1):{ans=(b+mod)%mod;break;}case(2):{ans=(b-a+2*mod)%mod;break;}case(3):{ans=(mod-a)%mod;break;}case(4):{ans=(mod-b)%mod;break;}case(5):{ans=(a-b+2*mod)%mod;break;}}cout<<ans<<endl;return 0;}
也可以利用矩阵的连乘~~~
#include<cstdio>int main(){int a,b,n,i,k,rep;while(scanf("%d%d%d",&a,&b,&n)!=EOF){int matrix[2][2]={1,0,-1,1};int ans[2][2]={1,0,0,1};k=n-2;if(a<0)a+=1000000007;if(b<0)b+=1000000007;for(;k;k>>=1){if(k&1){ans[0][0]=ans[0][0]*matrix[0][0]+ans[0][1]*matrix[1][0];//matrix's plusans[0][1]=ans[0][0]*matrix[0][1]+ans[0][1]*matrix[1][1];ans[1][0]=ans[1][0]*matrix[0][0]+ans[1][1]*matrix[1][0];ans[1][1]=ans[1][0]*matrix[0][1]+ans[1][1]*matrix[1][1];//ans=Mplus(ans,matrix);}matrix[0][0]=matrix[0][0]*matrix[0][0]+matrix[0][1]*matrix[1][0];//so do itmatrix[0][1]=matrix[0][0]*matrix[0][1]+matrix[0][1]*matrix[1][1];matrix[1][0]=matrix[1][0]*matrix[0][0]+matrix[1][1]*matrix[1][0];matrix[1][1]=matrix[1][0]*matrix[0][1]+matrix[1][1]*matrix[1][1];// matrix=Mplus(matrix,matrix);}rep=ans[1][0]*a+ans[1][1]*b;for(;rep<=0;rep+=1000000007);rep%=1000000007;printf("%d\n",rep);}return 0;}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: