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

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);
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值