您的位置:首页 > 其它

SDUT 2605 大幂和的分解,转化成R进制进行哈希 高效率打表(花样哈希)

2015-10-30 10:48 267 查看

A^X mod P


Time Limit: 5000ms Memory limit: 65536K 有疑问?点这里^_^

题目描述

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.

输入

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

输出

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.

示例输入

23 2 1 1 1 100 1003 15 123 2 3 1000 107


示例输出

Case #1: 14Case #2: 63


提示

来源

2013年山东省第四届ACM大学生程序设计竞赛

示例程序

这道题用矩阵快速幂暴力会超时的.

改用哈希的思想.

#include<bits/stdc++.h>//大幂的分解和 因为不停的求A的幂,所以肯定把算过的保存下来最合适。
#define LL long long
using namespace std;
LL dj[33355],dk[33333];
LL T,n,A,K,a,b,m,p;
int init()//打表,转换成R进制,减少时间复杂度
{
dj[0]=1;
for(int i=1;i<=33333;i++)
dj[i]=(dj[i-1]*A)%p;
dk[0]=1;
for(int i=1;i<=30000;i++)
dk[i]=dk[i-1]*dj[33333]%p;
}
int main()
{
while(~scanf("%d",&T))
{
int Case=0;
while(T--)
{
Case++;
scanf("%lld%lld%lld%lld%lld%lld%lld",&n,&A,&K,&a,&b,&m,&p);
init();
printf("Case #%d: ",Case);
LL sum=0;
LL ans=K;
for(int i=0;i<n;i++)
{                              //dj[k+j]=dj[j]*dk[k];<span id="transmark"></span>
sum=(sum+dj[ans%33333]*dk[ans/33333])%p;         //a^(k+j)=(a^k)*(a^j)
ans=(ans*a+b)%m;
}
printf("%lld\n",sum);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: