poj3243 Clever Y【BSGS模板】

解题思路:

BSGS模板题。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<ctime>
#include<vector>
#include<set>
#define ll long long
using namespace std;

const int N=50000;
const int H=999979;
int A,B,C,D;
int tot,first[H],nxt[N],val[N],deg[N];
int n,cnt,Pow[N];

int gcd(int a,int b)
{
    return b?gcd(b,a%b):a;
}

void exgcd(int a,int b,int &x,int &y)
{
    b?(exgcd(b,a%b,y,x),y-=a/b*x):(x=1,y=0);
}

int inv(int a,int b)
{
    int x,y;
    exgcd(a,b,x,y);
    return (x%b+b)%b;
}

void Insert(int d,int x)
{
    int u=x%H;
    for(int v=first[u];v;v=nxt[v])
        if(val[v]==x&&deg[v]<d)
        {
            deg[v]=d;
            return;
        }
    nxt[++tot]=first[u],first[u]=tot,val[tot]=x,deg[tot]=d;
}

int find(int x)
{
    int u=x%H;
    for(int v=first[u];v;v=nxt[v])
        if(val[v]==x)return deg[v];
    return -1;
}

int BSGS()
{
    memset(first,0,sizeof(first));
    cnt=tot=0,Pow[0]=D=1;
    int r,y,P=1;
    while((r=gcd(A,C))!=1)
    {
        if(B%r!=0)return -1;
        ++cnt,B/=r,C/=r;
        D=1ll*D*(A/r)%C;
    }
    B=1ll*B*inv(D,C)%C;
    for(n=1;n*n<C;n++);
    for(int i=1;i<=n;i++)
        Pow[i]=1ll*Pow[i-1]*A%C;
    for(int i=0;i<n;i++)
        Insert(i,1ll*Pow[i]*B%C);
    for(int i=1;i<=n;i++)
    {
        P=1ll*P*Pow[n]%C;
        if((y=find(P))!=-1)
            return i*n-y+cnt;
    }
    return -1;
}

bool check()
{
    for(int i=0,t=1;i<=10;i++)
    {
        if(t%C==B)
        {
            cout<<i<<'\n';
            return true;
        }
        t=1ll*t*A%C;
    }
    if(A==0)
    {
        puts("No Solution");
        return true;
    }
    return false;
}

int main()
{
    //freopen("lx.in","r",stdin);
    //freopen("lx.out","w",stdout);
    while(scanf("%d%d%d",&A,&C,&B)&&(ll)A+B+C>0)
    {
        A%=C,B%=C;
        if(check())continue;
        int ans=BSGS();
        if(ans==-1)puts("No Solution");
        else cout<<ans<<'\n';
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值