[BZOJ1467]Pku3243 clever Y(扩展BSGS)

来源:互联网 发布:犀牛o2o源码 编辑:程序博客网 时间:2024/06/10 00:40

题目描述

传送门

题解

这里写图片描述

代码

#include<algorithm>#include<iostream>#include<cstring>#include<cstdio>#include<cmath>#include<map>using namespace std;#define LL long longLL a,b,P;map <LL,LL> hash;LL gcd(LL a,LL b){    if (!b) return a;    else return gcd(b,a%b);}LL fast_pow(LL a,LL p){    LL ans=1LL;    for (;p;p>>=1LL,a=a*a%P)        if (p&1LL)            ans=ans*a%P;    return ans;}LL exbsgs(LL a,LL b,LL P){    if (b==1LL) return 0LL;    LL t=1LL,d=1LL,k=0LL;    while ((t=gcd(a,P))!=1LL)    {        if (b%t) return -1LL;        ++k,b/=t,P/=t,d=d*(a/t)%P;        if (b==d) return k;    }    hash.clear();    LL m=ceil(sqrt(P));LL a_m=fast_pow(a,m);    LL mul=b;    for (LL j=1;j<=m;++j)    {        mul=mul*a%P;        hash[mul]=j;    }    for (LL i=1;i<=m;++i)    {        d=d*a_m%P;        if (hash[d]) return i*m-hash[d]+k;    }    return -1LL;}int main(){    while (~scanf("%lld%lld%lld",&a,&P,&b))    {        if (!a&&!P&&!b) break;        LL ans=exbsgs(a%P,b%P,P);        if (ans!=-1LL) printf("%lld\n",ans);        else puts("No Solution");    }}

总结

抽空学一下手写hash

1 0