BSGS

· · 算法·理论

BSGS

(零)算法简介

题面

求最小的非负整数 x,满足 a^x \equiv b \pmod p。

对于所有的测试点,保证 2\le b,n < p<2^{31}, p 为质数。

题解

设:t=\lceil \sqrt p\ \rceil,x=i*t-j,其中 0\le j<t;

得 a^{i*t-j}\equiv b(mod\ p),得 (a^t)^i\equiv b*a^j(mod\ p);

然后枚举 j,将每个 b*a^j 放入 hash 或 map 内;

再枚举 i,查找是否有相等的 b*a^j。

时间复杂度 O(\sqrt p);经典的空间换取时间。

注意特判 a=0 的情况:若 b=0 则为 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

这题很恶心,首先我们化成 a^{k}\equiv x (\bmod p) 的形式,那么就是 BSGS。

具体来说,可以利用分块思想,枚举 i,j,a^{i*t-j}\equiv x,那么得出 a^{i*t}\equiv x*a^j,于是右边丢进 map 就可以快速查找了

分块思想就体现在:枚举了一个值,然后通过预处理,能够求出它的贡献,空间换时间。

然后特殊情况就是:运算过程中不能 /0,等比数列求和公式 q\not =1 。