Hdoj 1588 Gauss Fibonacci 【矩阵快速幂】
Gauss Fibonacci Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Problem Description Arithmetic progression: Fibonacci Numbers: The Gauss Fibonacci problem is described as follows: #include <cstdio>
#include <iostream>
#include <cstring>
using namespace std;
#define LL __int64
struct node{
LL num[3][3];
};
node e,a;
LL n,m,k,b;
node mul(node aa,node bb){
node c;
for(int i = 1; i < 3; ++i){
for(int j = 1; j < 3; ++j){
c.num[i][j] = 0;
for(int k = 1; k < 3; ++k){
c.num[i][j] = (c.num[i][j]+aa.num[i][k]*bb.num[k][j])%m;
}
}
}
return c;
}
node fa(node a,LL n){
node b = e;
while(n){
if(n&1) b = mul(a,b);
n >>= 1;
a = mul(a,a);
}
return b;
}
node add(node aa,node bb){
node c;
for(int i = 1; i < 3; ++i){
for(int j = 1; j < 3; ++j){
c.num[i][j] = (aa.num[i][j]+bb.num[i][j])%m;
}
}
return c;
}
node dg(node p,LL k){ //这里很巧
if(k == 1) return p;
else if(k&1) return add(dg(p,k-1),fa(p,k)); //这里就是A^(K⑴)+A^k
else return mul(dg(p,k>>1),add(fa(p,e));//这里就是 A^k+A^(k>>1);
}
int main(){
e.num[1][1] = e.num[2][2] = 1;
e.num[1][2] = e.num[2][1] = 0;
a.num[1][1] = a.num[1][2] = a.num[2][1] = 1; a.num[2][2] = 0;
while(cin >> k >> b >> n >> m){
node ak = fa(a,k);
node ab = fa(a,b);
node ans = dg(ak,n-1);
ans = add(e,ans);
ans = mul(ab,ans);
cout << ans.num[1][2]<< endl;
}
return 0;
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |