BZOJ 5296: [Cqoi2018]破解D-H协议 BSGS

模板题呀. 

code: 

#include <cstdio> 
#include <cstring>   
#include <cmath>    
#include <map>        
#include <algorithm>     
#define ll long long 
#define setIO(s) freopen(s".in","r",stdin) 
using namespace std;
int g,mod;    
map<int,int>bu;   
int qpow(int x,ll y) 
{
    int tmp=1; 
    for(;y;y>>=1,x=(ll)x*x%mod) 
        if(y&1) tmp=(ll)tmp*x%mod; 
    return tmp;   
}   
int bsgs(int y,int z) 
{         
    // y^x = z ( % mod)    
    int i,j,m=sqrt(mod)+1,tmp,f;  
    z%=mod;                   
    if(z==1) return 0;   
    bu.clear(),bu[z]=0;   
    for(tmp=z,i=1;i<m;++i) tmp=(ll)tmp*y%mod,bu[tmp]=i;                 
    for(tmp=1,f=qpow(y,m),i=1;i<=m+1;++i) 
    {       
        tmp=(ll)tmp*f%mod;    
        if(bu.count(tmp))  return i*m-bu[tmp];        
    }
}   
void solve() 
{
    int i,j,A,B;  
    scanf("%d%d",&A,&B);      
    int a=bsgs(g,A),b=bsgs(g,B);     
    printf("%d
",qpow(g,(ll)a*b));   
}
int main() 
{ 
    // setIO("input"); 
    int i,j,T; 
    scanf("%d%d%d",&g,&mod,&T);            
    while(T--) solve();  
    return 0;
}

  

原文地址:https://www.cnblogs.com/guangheli/p/12258462.html