【题目链接】
https://www.lydsy.com/JudgeOnline/problem.php?id=2242
【算法】
第一问用快速幂解决
第二问用exgcd解决
第三问用BSGS算法解决
【代码】
#include<bits/stdc++.h> using namespace std; typedef long long ll; ll T,K,y,z,p,q,x,g,ans; inline ll power(ll a,ll n,ll p) { ll b = a,ret = 1; while (n > 0) { if (n & 1) ret = 1ll * ret * b % p; b = 1ll * b * b % p; n >>= 1; } return ret; } inline ll exgcd(ll a,ll b,ll &x,ll &y) { ll g; if (b == 0) { x = 1; y = 0; return a; } else { g = exgcd(b,a%b,y,x); y -= a / b * x; return g; } } inline ll Baby_Step_Giant_Step(ll a,ll b,ll p) { ll i,j,t,val; map<ll,ll> mp; mp.clear(); b %= p; t = ceil(sqrt(p)); for (j = 0; j <= t; j++) { val = 1ll * b * power(a,j,p) % p; mp[val] = j; } a = power(a,t,p); if (a == 0) return b == 0 ? 1 : -1; for (i = 0; i <= t; i++) { val = power(a,i,p); j = mp.find(val) == mp.end() ? -1 : mp[val]; if (j >= 0 && i * t - j >= 0) return i * t - j; } return -1; } int main() { scanf("%lld%lld",&T,&K); while (T--) { scanf("%lld%lld%lld",&y,&z,&p); if (K == 1) printf("%lld ",power(y,z,p)); if (K == 2) { g = exgcd(y,p,x,q); if (z % g == 0) printf("%lld ",((x*z/g)%p+p)%p); else printf("Orz, I cannot find x! "); } if (K == 3) { ans = Baby_Step_Giant_Step(y,z,p); if (ans != -1) printf("%lld ",ans); else printf("Orz, I cannot find x! "); } } return 0; }