hdu5667 Sequence (矩阵快速幂+费马小定理)

Sequence

Sample Input

1

5 3 3 3 233

Sample Output

190

 

题解:

根据递推式可以发现,答案是以a为底数的一个值,所以对指数部分做快速幂得到k,最后答案就是qpow(a,k)%mod

根据递推式易得构造矩阵

 fn    c 1 b    fn-1
fn-1 = 1 0 0  * fn-2
 1     0 0 1      1

注意点,由于是对指数进行快速幂,根据费马小定理,

如果质数p,和满足gcd(a,p) == 1的任意数字a,那么就一定满足下面的式子:

所以

对于矩阵快速幂部分部分模p-1

对于快速幂部分模p(我就这在中招了,wa了好几发)

 

AC:代码

#include<bits/stdc++.h>
using namespace std;
#define mp make_pair
#define ss second
#define ff first
#define pb push_back
template <class T>
void read(T &x);
template<class T, class... U> void read(T &head, U &... tail)
{
    read(head), read(tail...);
}
typedef long long ll;
typedef unsigned long long ull;
typedef pair<pair<ll, ll>, pair<ll, ll> > pll;
const int inf = 0x3f3f3f3f;
const int maxn = 1e3 + 5;
ll n, a, b, c, mod,p;
struct matrix
{
    ll a[3][3];
    matrix()
    {
        memset(a, 0, sizeof a);
    }
};
matrix operator *(const matrix &x, const matrix &y) //矩阵相乘函数
{
    matrix res;
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
        {
            for(int k = 0; k < 3; k++)
            {
                res.a[i][j] += x.a[i][k] * y.a[k][j];
                res.a[i][j] %= mod;
            }

        }
    return res;
}
ll ksm(matrix base, ll n)
{
    matrix ans;
    for(int i = 0; i < 3; i++) ans.a[i][i] = 1;
    while(n)
    {
        if(n & 1) ans = ans * base;
        base = base * base;
        n >>= 1;
    }
    return ans.a[0][0]*b + ans.a[0][2];
}
ll qpow(ll base, ll n)
{
    ll ans = 1;
    while(n)
    {
        if(n & 1) ans = ans * base % p;
        base = base * base % p;
        n >>= 1;
    }
    return ans%p;
}

void work()
{
    read(n, a, b, c, p);
    mod=p-1;
    matrix base;
    base.a[0][0] = c;base.a[0][1] = 1;base.a[0][2] = b;
    base.a[1][0] = 1;base.a[2][2] = 1;
    cout<<qpow(a,ksm(base,n-2))<<endl;
}
int main(int argc, char const *argv[])
{
    int T;read(T);while(T--)
    work();
    return 0;
}
template <class T>
void read(T &x)
{
    static char ch;
    bool neg = false;
    while(!isdigit(ch = getchar())) (ch == '-') && (neg = true);
    for(x = ch - '0'; isdigit(ch = getchar()); x = x * 10 + ch - '0');
    (neg) &&(x = -x);
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值