BZOJ 2242: [SDOI2011]计算器( 快速幂 + 扩展欧几里德 + BSGS )

没什么好说的...

---------------------------------------------------------------------

#include<cstdio>
#include<cmath>
#include<map>
 
using namespace std;
 
typedef long long ll;
 
int MOD;
 
void gcd(int a, int b, int& d, int& x, int& y) {
if(!b) {
d = a;
x = 1;
y = 0;
} else {
gcd(b, a % b, d, y, x);
y -= x * (a / b);
}
}
 
//x^t % MOD
int power(int x, int t) {
int ret = 1;
for(; t; t >>= 1) {
if(t & 1) ret = ll(x) * ret % MOD;
x = ll(x) * x % MOD;
}
return ret;
}
 
//a^x = b(mod MOD)
int BSGS(int a, int b) {
if(a % MOD == 0) return -1;
int m = sqrt(MOD + 0.5), e = 1, v = power(a, MOD - m - 1);
map<int, int> x;
x[1] = 0;
for(int i = 1; i < m; i++) {
e = ll(e) * a % MOD;
if(!x.count(e)) x[e] = i;
}
for(int i = 0; i < m; i++) {
if(x.count(b)) return i * m + x[b];
b = ll(b) * v % MOD;
}
return -1;
}
 
int main() {
int T, K; scanf("%d%d", &T, &K);
while(T--) {
int a, b;
scanf("%d%d%d", &a, &b, &MOD);
if(K == 1)
   printf("%d\n", power(a, b));
else if(K == 2) {
int d, x, y;
gcd(a, MOD, d, x, y);
if(b % d != 0) puts("Orz, I cannot find x!");
else
printf("%d\n", (int) ((ll(x) * b / d % MOD + MOD) % MOD));
} else if(K == 3) {
int t = BSGS(a, b);
if(~t) printf("%d\n", t);
else 
   puts("Orz, I cannot find x!");
}
}
return 0;
}

---------------------------------------------------------------------

 

2242: [SDOI2011]计算器

Time Limit: 10 Sec  Memory Limit: 512 MB
Submit: 2111  Solved: 825
[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

 

posted @ 2015-09-17 20:54  JSZX11556  阅读(229)  评论(0编辑  收藏  举报