Codeforces_450B_Jzzhu and Sequences(循环节or矩阵快速幂)

来源:互联网 发布:三菱3uplc编程手册 编辑:程序博客网 时间:2024/05/21 06:19

题型:数论


题意:f1 = x, f2 = y ,fi = fi-1 + fi+1,求fn


分析:

       题目本身不难,可以简单的寻找到长度为6的循环节,也可以用矩阵快速幂来做,分分钟搞定,需要注意的是答案的取模,由于|x|, |y| ≤ 10^9,所以(fn+mod)%mod可能不够,至少要加俩次mod


代码:

循环节做法:

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<algorithm>#define mt(a,b) memset(a,b,sizeof(a))#define INF 0x3f3f3f3f#define MAXN 123456#define LL __int64using namespace std;const LL MOD = 1e9+7;LL x,y,n;int main() {    while(~scanf("%I64d%I64d",&x,&y)) {        scanf("%I64d",&n);        n %= 6;        LL ans;        if(n==1) {            ans = x;        }        if(n==2) {            ans = y;        }        if(n==3) {            ans = y-x;        }        if(n==4) {            ans = -x;        }        if(n==5) {            ans = -y;        }        if(n==0) {            ans = x-y;        }        ans = (ans+MOD+MOD)%MOD;        printf("%I64d\n",ans);    }    return 0;}


矩阵快速幂做法:

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<cstdlib>#include<queue>#include<algorithm>#define LL __int64#define mt(a,b) memset(a,b,sizeof(a))#define M 4using namespace std;const LL mod = 1e9+7;class Matrix { //矩阵快速幂    typedef LL typev;public:    typev val[M][M];    void zero() {        memset(val,0,sizeof(val));    }    void unit() {        zero();        for(int i=0; i<M; i++) val[i][i]=1;    }};int LEN;Matrix operator * (const Matrix &a,const Matrix &b) {    Matrix tmp;    tmp.zero();    for(int k=0; k<LEN; k++)        for(int i=0; i<LEN; i++) {            if(a.val[i][k])                for(int j=0; j<LEN; j++) {                    tmp.val[i][j]+=a.val[i][k]*b.val[k][j];                    tmp.val[i][j]%=mod;                }        }    return tmp;}Matrix operator ^ (Matrix &a,LL p) {    Matrix tmp;    tmp.unit();    while(p) {        if(p&1) tmp=tmp*a;        a=a*a;        p>>=1;    }    return tmp;}LL x,y,n;int main() {    while(~scanf("%I64d%I64d",&x,&y)){        scanf("%I64d",&n);        if(n == 1){            printf("%I64d\n",(x+mod+mod)%mod);            continue;        }        if(n == 2){            printf("%I64d\n",(y+mod+mod)%mod);            continue;        }        LEN = 2;        Matrix cef;        cef.zero();        cef.val[0][0] = 1;        cef.val[0][1] = -1;        cef.val[1][0] = 1;        cef = cef ^ (n-2);        LL ans = y * cef.val[0][0] + x * cef.val[0][1];        ans = (ans + mod + mod) % mod;        printf("%I64d\n",ans);    }    return 0;}


0 0
原创粉丝点击