您的位置:首页 > 其它

BZOJ2242 SDOI2011 计算器

2017-08-08 15:18 459 查看
2242: [SDOI2011]计算器

Time Limit: 10 Sec Memory Limit: 512 MB

Submit: 4351 Solved: 1678

[Submit][Status][Discuss]

Description

你被要求设计一个计算器完成以下三项任务:

1、给定y,z,p,计算Y^Z Mod P 的值;

2、给定y,z,p,计算满足xy≡ Z ( mod P )的最小非负整数;

3、给定y,z,p,计算满足Y^x ≡ Z ( mod P)的最小非负整数。

Input

输入包含多组数据。

第一行包含两个正整数T,K分别表示数据组数和询问类型(对于一个测试点内的所有数据,询问类型相同)。

以下行每行包含三个正整数y,z,p,描述一个询问。

Output

对于每个询问,输出一行答案。对于询问类型2和3,如果不存在满足条件的,则输出“Orz, I cannot find x!”,注意逗号与“I”之间有一个空格。

Sample Input

【样例输入1】

3 1

2 1 3

2 2 3

2 3 3

【样例输入2】

3 2

2 1 3

2 2 3

2 3 3

【数据规模和约定】

对于100%的数据,1<=y,z,p<=10^9,为质数,1<=T<=10。

Sample Output

【样例输出1】

2

1

2

【样例输出2】

2

1

0

HINT

Source

第一轮day1

/**************************************************************
Problem: 2242
User: Twi_etn
Language: C++
Result: Accepted
Time:2340 ms
Memory:3284 kb
****************************************************************/

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<map>
#define LL long long
#define MAXN 1001001
using namespace std;
int P,y,z,k,T,n;
map<int,int> mp;
LL Fast_Pow(LL a,LL b,LL P){
LL ret=1,c=a;
while(b){
if(b&1) ret=ret*c,ret%=P;
c=c*c;c%=P; b>>=1;
}
return ret;
}
void BSGS(int y,int z,int Mod){
if(y==0&&z==0){ printf("1\n");return; }
if(y==0&&z!=0){ printf("Orz, I cannot find x!\n");return; }
mp.clear();
int tmp=1,p=Fast_Pow(y,Mod-2,Mod),k=ceil(sqrt(Mod));
mp[z]=k+1;
for(int i=1;i<k;i++){
tmp=(LL)tmp*p%Mod;
int t=(LL)tmp*z%Mod;
if(!mp[t]) mp[t]=i;
}
tmp=1;p=Fast_Pow(y,k,Mod);
for(int i=0;i<k;i++,tmp=(LL)tmp*p%Mod){
if(mp[tmp]){
if(mp[tmp]==k+1) printf("%d\n",i*k);
else printf("%d\n",i*k+mp[tmp]);
return ;
}
}
printf("Orz, I cannot find x!\n");
}
int main(){
scanf("%d%d",&n,&T);
while(n--){
scanf("%d%d%d",&y,&z,&P);y%=P;
if(T==1) printf("%d\n",Fast_Pow(y,z,P));
else if(T==2){
z%=P;
if(y==0&&z!=0) printf("Orz, I cannot find x!\n");
else printf("%d\n",(LL)z*Fast_Pow(y,P-2,P)%P);//P 保证是质数 y、P一定互质 欧拉定理
//a^phi(p)≡1 (Mod p)  ---->  a*a^phi(p)-1 ≡1 (Mod p) P是质数时,phi(p)=p-1
}
else z%=P,BSGS(y,z,P);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  快速幂 BSGS