So Easy! HDU - 4565(构造共轭+矩阵快速幂)

So Easy! HDU - 4565

A sequence S n is defined as:

Sn=(a+b)n%m S n = ⌈ ( a + b ) n ⌉ % m

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
题意:

求上面的公式

分析:

直接看这篇文章吧,照着这个题写的讲解

斐波那契数列通项公式推导及其类似构造共轭公式反求递推式

得到递推式

fn=2afn1+(ba2)fn2 f n = 2 a ⋅ f n − 1 + ( b − a 2 ) ⋅ f n − 2

打表发现这个递推式取模好像没有循环节因此只能老老实实用矩阵快速幂

(fnfn1)=(2a1baa0)(fn1fn2)(1) (1) ( f n f n − 1 ) = ( 2 a b − a a 1 0 ) ⋅ ( f n − 1 f n − 2 )

(fnfn1)=(2a1baa0)n1(f1f0)(2) (2) ( f n f n − 1 ) = ( 2 a b − a a 1 0 ) n − 1 ⋅ ( f 1 f 0 )

code:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <string>
#include <math.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5+10;
int a,b,n,m;
struct Matrix{
    int mm[3][3];
};
Matrix mul(Matrix aa,Matrix bb){
    Matrix ans;
    for(int i = 0; i < 2; i++){
        for(int j = 0; j < 2; j++){
            ans.mm[i][j] = 0;
            for(int k = 0; k < 2; k++){
                ans.mm[i][j] = (ans.mm[i][j] + aa.mm[i][k] * bb.mm[k][j] % m + m) % m;
            }
        }
    }
    return ans;
}
Matrix q_pow(Matrix aa,int bb){
    Matrix ans;
    memset(ans.mm,0,sizeof(ans.mm));
    for(int i = 0; i < 2; i++){
        ans.mm[i][i] = 1;
    }
    while(bb){
        if(bb & 1)
            ans = mul(ans,aa);
        bb >>= 1;
        aa = mul(aa,aa);
    }
    return ans;
}
int main(){
    while(~scanf("%d%d%d%d",&a,&b,&n,&m)){
        Matrix ans;
        ans.mm[0][0] = 2 * a % m;
        ans.mm[0][1] = b - a * a;
        ans.mm[1][0] = 1;
        ans.mm[1][1] = 0;
        ans = q_pow(ans,n-1);
        printf("%d\n",(ans.mm[0][0] * 2 * a % m + ans.mm[0][1] * 2 % m + m) % m);
    }
    return 0;
}

同类型题目Best Solver HDU - 5451
这道题取模有循环节,处理起来就相对简单些了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值