【矩阵快速幂】HDU_4565_So Easy!

来源:互联网 发布:九九乘法表js编程 编辑:程序博客网 时间:2024/06/05 00:59

So Easy!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 5051    Accepted Submission(s): 1660


Problem Description
  A sequence Sn is defined as:

Where a, b, n, m are positive integers.┌x┐is the ceil of x. For example, ┌3.14┐=4. You are to calculate Sn.
  You, a top coder, say: So easy! 
 

Input
  There are several test cases, each test case in one line contains four positive integers: a, b, n, m. Where 0< a, m < 215, (a-1)2< b < a2, 0 < b, n < 231.The input will finish with the end of file.
 

Output
  For each the case, output an integer Sn.
 

Sample Input
2 3 1 20132 3 2 20132 2 1 2013
 

Sample Output
4144
 

Source
2013 ACM-ICPC长沙赛区全国邀请赛——题目重现
 

Recommend
zhoujiaqi2010
/*化一化就转化成a^n+b^n%m的问题跟lightOJ1070一样*/#include <bits/stdc++.h>using namespace std;typedef long long LL;const int maxn=2;typedef struct node{    LL a[maxn][maxn];    node(){        memset(a,0,sizeof(a));    }}Matrix;Matrix multiply(Matrix x,Matrix y,LL mod){    Matrix ans;    for(int i=0;i<maxn;i++){        for(int j=0;j<maxn;j++){            for(int k=0;k<maxn;k++){                ans.a[i][j]=(ans.a[i][j]+x.a[i][k]*y.a[k][j])%mod;            }        }    }    return ans;}Matrix quickpow(Matrix x,int a,int mod){    Matrix ans;    for(int i=0;i<maxn;i++)        ans.a[i][i]=1;    while(a){        if(a&1)            ans=multiply(ans,x,mod);        x=multiply(x,x,mod);        a>>=1;    }    return ans;}int main(){    LL a,b,m;    int n;    while(~scanf("%I64d%I64d%d%I64d",&a,&b,&n,&m)){        if(n<3){            if(n==0) printf("%I64d\n",2%m);            else if(n==1) printf("%I64d\n",(2*a)%m);            else if(n==2) printf("%I64d\n",(2*a*a+2*b)%m);            continue;        }        Matrix base,x;        base.a[0][0]=2*a*a+2*b;base.a[0][1]=2*a;        x.a[0][0]=2*a%m;x.a[0][1]=1;x.a[1][0]=(b-a*a%m+m)%m;x.a[1][1]=0;//没取模就WA了        Matrix ans=multiply(base,quickpow(x,n-2,m),m);        printf("%I64d\n",ans.a[0][0]);    }}

原创粉丝点击