# BZOJ3122 [Sdoi2013]随机数生成器 【BSGS】

3

7 1 1 3 3

7 2 2 2 0

7 2 2 2 1

1

3

-1

## 提示

0<=a<=P-1,0<=b<=P-1,2<=P<=10^9

## 题解

BSGS时，开根要向上取整，保证查找真的完全了

#include<iostream>
#include<cstdio>
#include<cmath>
#include<map>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<' '; puts("");
using namespace std;
const int maxn = 100005,maxm = 100005,INF = 1000000000;
int out = 0,flag = 1; char c = getchar();
while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
return out * flag;
}
LL P;
map<LL,LL> mp;
LL qpow(LL a,LL b){
LL ans = 1;
for (; b; b >>= 1,a = a * a % P)
if (b & 1) ans = ans * a % P;
return ans % P;
}
LL inv(LL a){
return qpow(a,P - 2);
}
void solve1(LL A,LL B,LL X,LL T){
LL ans = ((T - X) % P * inv(B) % P + P) % P;
printf("%lld\n",ans + 1);
}
LL BSGS(LL a,LL b){
mp.clear();
if (a % P == 0) return -2;
LL m = (LL)ceil(sqrt(P)),ans;
for (int i = 0; i <= m; i++){
if (i == 0){
ans = b % P;
mp[ans] = i;
}
else {
ans = ans * a % P;
mp[ans] = i;
}
}
LL t = qpow(a,m); ans = t;
for (int i = 1; i <= m; i++){
if (i != 1) ans = ans * t % P;
if (mp.count(ans)){
ans = ((i * m - mp[ans]) % P + P) % P;
return ans;
}
}
return -2;
}
void solve2(LL A,LL B,LL X,LL T){
LL tmp = B * inv(A - 1) % P;
LL a = A,b = (T + tmp) % P * inv(X + tmp) % P;
printf("%lld\n",BSGS(a,b) + 1);
}
int main(){
while (T--){
if (X1 == t) puts("1");
else if (a == 0){
if (t == b) puts("2");
else puts("-1");
}
else if (a == 1){
if (b == 0) puts("-1");
else solve1(a,b,X1,t);
}
else solve2(a,b,X1,t);
}

return 0;
}


posted @ 2018-03-19 14:20  Mychael  阅读(183)  评论(0编辑  收藏  举报