第四届山东省赛 A^X mod P [预处理]【思维】

题目链接:http://acm.upc.edu.cn/problem.PHP?id=2219
————————————————————————————————————
2219: A^X mod P
Time Limit: 5 Sec Memory Limit: 128 MB
Submit: 142 Solved: 28
[Submit][Status][Web Board]
Description
It’s easy for ACMer to calculate A^X mod P. Now given seven integers n, A, K, a, b, m, P, and a function f(x) which defined as following.
f(x) = K, x = 1
f(x) = (a*f(x-1) + b)%m , x > 1

Now, Your task is to calculate
( A^(f(1)) + A^(f(2)) + A^(f(3)) + …… + A^(f(n)) ) modular P.
Input
In the first line there is an integer T (1 < T <= 40), which indicates the number of test cases, and then T test cases follow. A test case contains seven integers n, A, K, a, b, m, P in one line.
1 <= n <= 10^6
0 <= A, K, a, b <= 10^9
1 <= m, P <= 10^9
Output
For each case, the output format is “Case #c: ans”.
c is the case number start from 1.
ans is the answer of this problem.
Sample Input
2
3 2 1 1 1 100 100
3 15 123 2 3 1000 107
Sample Output
Case #1: 14
Case #2: 63

————————————————————————————————————

题目大意:
就是给你7个数:
n,A,K,a,b,m,P
一个公式:
f(x)={ K(af(x1)+b)%m,x=1,x>1

问:
(Af(1)+Af(2)+Af(3)+......+Af(n))modP.

解题思路:
其实思路很好构建 ,
只要求出 f(i) 然后 O(nlogn) 的快速幂就能求解

但是这题卡了 log ,所以不能快速幂

对于求一次幂 用快速幂会非常快 但是求多次就不是很快了

我们要先预处理出所有 {Ax|x[1,P]}

发现根本存不下 , P109
但是我们可以预处理出
{Ax|x[1,P]}

{(AP)x|x[1,P]}
这样我们就可以通过一次相乘,开快速求出 Z{Ax|x[1,P]}

这样下来复杂度就变成了 O(Tn)

附本题代码

——————————————————————————————————————————————————————————————

#include<bits/stdc++.h>

using namespace std;
typedef long long int LL;
/********************************/

LL Ai[100005];
LL A1e5i[100005];

int main(){
    int _ = 1,kcase = 0;
    scanf("%d",&_);
    while(_--){
        int n, A, K, a, b, m, P;
        scanf("%d%d%d%d%d%d%d",&n, &A, &K, &a, &b, &m, &P);
        Ai[0]=1;
        Ai[1]=A;
        for(int i=1;i<=100000;i++){
            Ai[i]=Ai[i-1]*A%P;
        }
        A1e5i[0]=1;
        A1e5i[1]=Ai[100000];
        for(int i=2;i<=100000;i++){
            A1e5i[i]=A1e5i[1]*A1e5i[i-1]%P;
        }
        LL ans =0,tmp=K;
        for(int i=1;i<=n;i++){
            ans+=Ai[tmp%100000]*A1e5i[tmp/100000];
            (ans>P)?ans%=P:true;
            tmp=tmp*a+b,tmp%=m;
        }

        printf("Case #%d: ",++kcase);
        printf("%lld\n",ans);

    }
    return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值