BSGS

时间:2022-06-26 03:45:29

北上广深/拔山盖世算法。

yaT+b = z mod p

p为质数,Hash表存b,枚举a,复杂度p0.5

记得特判y = 0的情况。

 inline void solve3() {
Hash::clear();
//mp.clear();
scanf("%lld%lld%lld", &Y, &Z, &MO);
Z %= MO;
Y %= MO;
/// BSGS
if(Y == ) {
if(!Z) printf("1\n");
else printf("Orz, I cannot find x!\n");
return;
}
int T = sqrt(MO);
LL x = , y = ;
for(int i = ; i < T; i++) {
Hash::insert(x, i);
//mp[x] = i;
x = x * Y % MO;
}
x = qpow(x, MO - ); /// x = 1 / (Y ^ T)
for(int i = ; i <= MO / T; i++) {
int t = Hash::find(Z * y % MO);
if(t != -) {
printf("%lld\n", 1ll * i * T + t);
return;
}
y = y * x % MO;
}
printf("Orz, I cannot find x!\n");
return;
}

模板