BSGS
(零)算法简介
题面
求最小的非负整数 ,满足 。
对于所有的测试点,保证 , 为质数。
题解
设:,,其中 ;
得 ,得 ;
然后枚举 ,将每个 放入 hash 或 map 内;
再枚举 ,查找是否有相等的 。
时间复杂度 ;经典的空间换取时间。
注意特判 的情况:若 则为 1,否则无解。
#include<bits/stdc++.h>
#define frein freopen("in.txt","r",stdin);
#define freout freopen("out.txt","w",stdout);
#define fre(p) freopen(#p".in","r",stdin),freopen(#p".out","w",stdout);
#define outa(LL,RR,AA) {for(rg O=LL;O<=RR;O++)cout<<AA[O]<<" ";cout<<endl;}
#define outm(LL1,RR1,LL2,RR2,AA) {for(rg U=LL1;U<=RR1;U++){for(rg V=LL2;V<=RR2;V++)cout<<AA[U][V]<<" ";cout<<endl;}cout<<endl;}
#define BZ printf("--------\n");
#define rg register int
#define int long long
using namespace std;
int mo,x,y,ans,z;
unordered_map<int,int>t;
int ksm(int x,int y){
int res=1;
while(y){
if(y&1)res=res*x%mo;
x=x*x%mo,y>>=1;
}
return res;
}
int bsgs(int x,int y,int mo){
z=ceil(sqrt(mo));t.clear();y=y%mo;
for(int i=0,s=1;i<z;i++,s=s*x%mo)t[y*s%mo]=i;
x=ksm(x,z);
if(x==0)return y==0?1:-1;
for(int i=0,s=1,j;i<=z;i++,s=s*x%mo){
j=t.find(s)==t.end()?-1:t[s];
if(j>=0&&i*z-j>=0)return i*z-j;
}
return -1;
}
signed main(){
cin>>mo>>x>>y;ans=bsgs(x,y,mo);
if(ans==-1)cout<<"no solution";
else cout<<ans;
return 0;
}(一)应用与习题
P3306 [SDOI2013] 随机数生成器
分讨特殊情况+BSGS
这题很恶心,首先我们化成 的形式,那么就是 BSGS。
具体来说,可以利用分块思想,枚举 ,那么得出 ,于是右边丢进 map 就可以快速查找了
分块思想就体现在:枚举了一个值,然后通过预处理,能够求出它的贡献,空间换时间。
然后特殊情况就是:运算过程中不能 ,等比数列求和公式 。