Codeforces 450B Jzzhu and Sequences(矩阵快速幂)

来源:互联网 发布:中国大学生网络党课 编辑:程序博客网 时间:2024/05/22 23:58

根据题目所给公式推导出base矩阵为1    1

     -1   0,接下来就可以套用快速幂矩阵模板。

#include<iostream>#include<cstdio>#include<algorithm>#include<cmath>#include<queue>#include<cstring>#define ll long longusing namespace std;const int mo = 1e9 + 7; struct node{ll m[2][2];};ll x,y;node cmp(node a, node b){node te;for(int i = 0; i < 2; i++)for(int j = 0; j < 2; j++){te.m[i][j]=0;for(int k = 0; k< 2; k++){te.m[i][j] += a.m[i][k] * b.m[k][j];//;long long防止数据溢出 te.m[i][j] %= mo; }}return te;}node powermod(ll n){node ans,base;base.m[0][0] = base.m[0][1] = 1;base.m[1][0] = -1;    base.m[1][1] = 0;        ans.m[0][0] = y - x;ans.m[1][1] = x;    ans.m[0][1] = ans.m[1][0] = y;// ans 初始化为单位矩阵    while(n){    if(n&1) ans = cmp(ans, base);    n >>= 1;    base=cmp(base, base);}return ans;} int main(){ll n;node te;scanf("%I64d%I64d%I64d",&x,&y,&n);te = powermod(n-1);ll tt = te.m[1][1];while(tt < 0)tt += mo;printf("%I64d\n", tt);return 0;}