【NEUQ OJ】 2164: Icebound and Sequence (矩阵快速幂 2019河北省省赛)

  • 题目描述

Icebound hates math. But Imp loves math. One day, Imp gave icebound a problem.
The problem is as follows.
在这里插入图片描述
For given q,n,p, you need to help icebound to calculate the value of S.

  • 输入描述

The first line contains an integer T, denoting the number of test cases.
The next T lines, each line contains three integers q,n,p, separated by spaces.
在这里插入图片描述

  • 输出描述

For each test case, you need to output a single line with the integer S.

  • 样例输入
2
2 3 100
511 4 520
  • 样例输出
14
184
  • 题意

题意很简单,就是求等比数列前n项和%p,q是首项和公比,n是项数

  • 思路

设等比数列第n项为Sn,第n-1项为Sn-1,则第n项与第n-1项之间存在线性关系:Sn = Sn-1 + a1 * q ^ (n - 1),符合矩阵快速幂的模板,其初始矩阵为:
1 1
0 q
对此矩阵执行快速幂即可,如果不会矩阵快速幂的请点击矩阵快速幂详解

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll mod;
struct node{
    ll a[2][2];
};

node arr(node y, node z){
    node x;
    memset(x.a, 0, sizeof(x.a));
    for(int i = 0; i < 2; i++)
        for(int k = 0; k < 2; k++)
            for(int j = 0; j < 2; j++)
                x.a[i][j] = (x.a[i][j] + y.a[i][k] * z.a[k][j]) % mod;
    return x;
}

node quick(node base, ll n){
    node x;
    memset(x.a, 0, sizeof(x.a));
    x.a[0][0] = 1;
    x.a[1][1] = 1;
    while(n){
        if(n & 1) x = arr(x, base);
        base = arr(base, base);
        n >>= 1;
    }
    return x;
}

int main(){
    ll t;
    scanf("%lld", &t);
    while(t--){
        ll q, n, p;
        scanf("%lld%lld%lld", &q, &n, &p);
        mod = p;
        node x, y;
        y.a[0][0] = 1;
        y.a[0][1] = 1;
        y.a[1][0] = 0;
        y.a[1][1] = q;
        x = quick(y, n - 1);
        printf("%lld\n", ((x.a[0][0] * q) % mod + ((q * q) % mod *x.a[0][1]) % mod) % mod);
    }

    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值