题目链接:http://acm.upc.edu.cn/problem.php?id=2219
2219: A^X mod P
Time Limit: 5 Sec Memory Limit: 128 MBSubmit: 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
23 2 1 1 1 100 1003 15 123 2 3 1000 107
Sample Output
Case #1: 14Case #2: 63思路:刚看到这题想法是快速幂,但是仔细看了之后发现会超时,快速幂计算一个比较快,如果计算多个就没有这么快了;
那么我们的做法是预处理(打表)来降低时间复杂度;
f(x)最大不超过1e9;现打表出 A^1 mod p, A^2 mod p...........A^50000 mod p;
再打表出 (A^50000)^1%p (A^50000)^2%p (A^50000)^3%p.... (A^50000)^50000%p
然后查表就A了;
#include <iostream>
#include <stdio.h>
#include <string>
#include <string.h>
#include <algorithm>
const int N=1e6+100;
using namespace std;
typedef long long ll;
ll f[N];
ll X[500005];
ll Y[500005];
int main()
{
int T,test=1;
cin>>T;
while(T--)
{
ll n,A,K,a,b,m,p;
ll cnt=0;
cin>>n>>A>>K>>a>>b>>m>>p;
// a%=m,b%=m;
f[1]=K;
for(int i=2;i<=n;i++)
f[i]=(((a%m)*(f[i-1]%m))%m+b%m)%m;
X[0]=1;
for(int i=1;i<=50000;i++)X[i]=(A%p*X[i-1])%p;
Y[0]=1;
for(int i=1;i<=50000;i++)Y[i]=(X[50000]%p*Y[i-1]%p)%p;
for(int i=1;i<=n;i++)
{
cnt+=Y[f[i]/50000]*X[f[i]%50000];
cnt%=p;
}
cout<<"Case #"<<test++<<": ";
cout<<cnt<<endl;
}
return 0;
}
/**************************************************************
Problem: 2219
User: liusuangeng
Language: C++
Result: Accepted
Time:3032 ms
Memory:16892 kb
****************************************************************/