【矩阵快速幂】HDU_4565_So Easy!

本文介绍了一种使用矩阵快速幂解决特定数列问题的方法。针对给定的数列公式,通过矩阵运算加速大数指数计算,并提供了完整的C++代码实现。适用于解决形如Sn=a^n+b^n%m的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 S n 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 S n.
  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 < 2 15, (a-1) 2< b < a 2, 0 < b, n < 2 31.The input will finish with the end of file.
 

Output
  For each the case, output an integer S n.
 

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

Sample Output
  
4 14 4
 

Source
 

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]);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值