hdu 4565 So Easy! 递推+矩阵快速幂

So Easy!

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


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   |   We have carefully selected several similar problems for you:   4830  4829  4828  4827  4826 
 


#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int MAXN=4;
ll n,m,a,b;
struct Matrix
{
    ll matrix[MAXN][MAXN];
}E;
Matrix matrix_mul(Matrix a,Matrix b)
{
    Matrix c;
    for(int i=1;i<=2;i++)
        for(int j=1;j<=2;j++)
        {
            c.matrix[i][j]=0;
            for(int k=1;k<=2;k++)
                if(a.matrix[i][k] && b.matrix[k][j])
                {
                    c.matrix[i][j]+=a.matrix[i][k]*b.matrix[k][j];
                    if(c.matrix[i][j]>=m)
                        c.matrix[i][j]%=m;
                    if(c.matrix[i][j]<0)
                        c.matrix[i][j]=c.matrix[i][j]%m+m;
                }
        }
    return c;
}
Matrix matrix_pow(Matrix a,int k)
{
    Matrix c=E;
    while(k)
    {
        if(k&1)
            c=matrix_mul(c,a);
        a=matrix_mul(a,a);
        k>>=1;
    }
    return c;
}
int main()
{
    //freopen("text.txt","r",stdin);
    while(~scanf("%I64d%I64d%I64d%I64d",&a,&b,&n,&m))
    {
        if(n==1)
        {
            printf("%I64d\n",2*a%m);
            continue;
        }
        for(int i=1;i<=2;i++)
            E.matrix[i][i]=1;
        Matrix A;
        A.matrix[1][1]=2*a; A.matrix[1][2]=b-a*a;
        A.matrix[2][1]=1;   A.matrix[2][2]=0;
        A=matrix_pow(A,n-1);
        printf("%I64d\n",((A.matrix[1][1]*2*a+A.matrix[1][2]*2)%m+m)%m);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值