[BZOJ1467]Pku3243 clever Y

传送门

传送门

exbsgs模板。

//Achen
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<cstdio>
#include<queue>
#include<cmath>
#include<map>
#define For(i,a,b) for(int i=(a);i<=(b);i++)
#define Rep(i,a,b) for(int i=(a);i>=(b);i--)
typedef long long LL;
using namespace std;
LL x,y,z; 

template<typename T>void read(T &x)  {
    char ch=getchar(); x=0; T f=1;
    while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') f=-1,ch=getchar();
    for(;ch>='0'&&ch<='9';ch=getchar()) x=x*10+ch-'0'; x*=f;
}

void exgcd(LL a,LL b,LL &d,LL &x,LL &y) {
    if(!b) { d=a; x=1; y=0; return; }
    exgcd(b,a%b,d,y,x); y-=a/b*x;
}

LL get_inv(LL a,LL p) {
    LL x,y,d;
    exgcd(a,p,d,x,y); return (x%p+p)%p;
}

map<LL,int>mp;
void exbsgs(LL a,LL c,LL p) {
    LL k=0,t=1,d,x,y,m,bs,a_m,inv;
    if(c==1) { puts("0"); return; }
    for(;;) {
        exgcd(a,p,d,x,y);
        if(d==1) break;
        if(c%d) { puts("No Solution"); return; }
        c/=d; p/=d; k++; (t*=a/d)%=p;
        if(t==c) { printf("%lld\n",k); return; } 
    }
    m=sqrt(p); mp.clear(); 
    bs=t,a_m=1;
    For(i,1,m) {
        (bs*=a)%=p;
        (a_m*=a)%=p;
        if(bs==c) { printf("%lld\n",i+k); return; }
        if(!mp[bs]) mp[bs]=i;
    }
    inv=get_inv(a_m,p);
    For(i,1,m+1) {
        (c*=inv)%=p;
        if(mp[c]) 
        { printf("%lld\n",((LL)i*m+mp[c]+k)); return; }
    }
    puts("No Solution");  
}

#define DEBUG
int main() {
#ifdef DEBUG
    freopen("1467.in","r",stdin);
    freopen("1467.out","w",stdout);
#endif
    for(;;) {
        read(x); read(z); read(y);
        if(!x&&!y&&!z) break;
        exbsgs(x,y,z);
    }
    return 0;
}
/*
5827 1447 924
6151 4517 1533
34 471 328
2237 2927 1621
6176 184 23
10391 14386 8343
9767 189200692 34854003
751 178113329 14879682
2574947 917524138 881310617
26926726 924715151 598451731
5495227 118152703 23838774
891601 847124342 830228635
647417 149565974 35242619
2634607 112198727 48203858
9999999 700000000 145229055
1801 813460328 677191737
4127 994552551 712177282
8419 997917352 760474435
1005883 864559096 530825483
1000003 931170240 194760799
0 0 0
*/
View Code

 

posted @ 2018-01-29 18:03  啊宸  阅读(141)  评论(0编辑  收藏  举报