最近在学习矩阵快速幂,以前还觉得快速幂挺难写的,现在看来真的是好简单了。。毕竟以前菜
把我们要递推的数放在一个矩阵里,然后构造一个递推矩阵进行矩阵乘法。。。
#include<stdio.h> #include<vector> using namespace std; typedef long long ll; const int mod=1e9+7; typedef vector<ll> vec; typedef vector<vec> mat; mat mul(mat &a,mat &b){ mat c(a.size(),vec(b[0].size())); for(int i=0;i<a.size();i++){ for(int j=0;j<b[0].size();j++){ for(int k=0;k<a[0].size();k++){ c[i][j]=(c[i][j]+a[i][k]*b[k][j])%mod; } } } return c; } int main(){ #ifndef ONLINE_JUDGE freopen("in.txt","r",stdin); #endif ll x,y; int n; scanf("%I64d%I64d%d",&x,&y,&n); x=(x+mod)%mod;y=(y+mod)%mod; mat a(1,vec(2)),b(2,vec(2)); a[0][0]=x;a[0][1]=y; b[0][0]=0;b[0][1]=-1; b[1][0]=1;b[1][1]=1; n--; while(n>0){ if(n&1) a=mul(a,b); b=mul(b,b); n>>=1; } while(a[0][0]<0) a[0][0]+=mod; printf("%I64d\n",a[0][0]); }
CodeForces 450B Jzzhu and Sequences
原文地址:http://blog.csdn.net/lj94093/article/details/45799137