BZOJ5296 [CQOI2018] 破解D-H协议 【数学】【BSGS】

题目分析:

  裸题。

代码:

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long ll;
 5 
 6 const int BASE = 10045601;
 7 
 8 #define mp make_pair
 9 
10 ll g,p;
11 ll srt = 50000;
12 vector<pair<int,ll> > hash[10200000];
13 
14 ll fast_pow(ll now,ll pw){
15     if(pw == 1) return now;
16     ll z = fast_pow(now,pw/2);
17     z *= z ; z %= p;
18     if(pw & 1)z *= now,z %= p;
19     return z;
20 }
21 
22 void CreatHash(){
23     ll xm = fast_pow(g,srt);
24     ll hh = xm;
25     for(ll i=1;(i-1)*srt<=INT_MAX;i++,hh = (hh*xm)%p){
26     hash[hh % BASE].push_back(mp(i,hh));
27     }
28 }
29 
30 void read(){
31     scanf("%lld%lld",&g,&p);
32     CreatHash();
33 }
34 
35 ll solve(ll now){
36     ll hh = g;
37     for(int i=1;i<=50000;i++,hh=(hh*g)%p){
38     ll nowp = (hh*now)%p;
39     for(int j=0;j<hash[nowp%BASE].size();j++){
40         ll out = hash[nowp%BASE][j].second;
41         if(out == nowp){
42         out = hash[nowp%BASE][j].first;
43         return out*srt-i;
44         }
45     }
46     }
47 }
48 
49 void work(){
50     int n;scanf("%d",&n);
51     for(int i=1;i<=n;i++){
52     ll a,b; scanf("%lld%lld",&a,&b);
53     ll hh = solve(a);
54     ll key = fast_pow(b,hh);
55     printf("%lld\n",key);
56     }
57 }
58 
59 int main(){
60     read();
61     work();
62     return 0;
63 }

猜你喜欢

转载自www.cnblogs.com/Menhera/p/8934061.html