poj3243:Clever Y(BSGS)

传送门

题意:

AxB(modC)

的最小X解。

题解:
BSGS 。
互质很好想。

对于不互质:

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
namespace IO
{
    streambuf *ib,*ob;int buf[50];
    inline void init()
    {
        ios::sync_with_stdio(false);
        cin.tie(NULL);cout.tie(NULL);
        ib=cin.rdbuf();ob=cout.rdbuf();
    }
    inline int read()
    {
        char ch=ib->sbumpc();int i=0,f=1;
        while(!isdigit(ch)){if(ch=='-')f=-1;ch=ib->sbumpc();}
        while(isdigit(ch)){i=(i<<1)+(i<<3)+ch-'0';ch=ib->sbumpc();}
        return i*f;
    }
    inline void W(int x)
    {
        if(!x){ob->sputc('0');ob->sputc('\n');return;}
        if(x<0){ob->sputc('-');x=-x;}
        while(x)buf[++buf[0]]=x%10,x/=10;
        while(buf[0])ob->sputc(buf[buf[0]--]+'0');
        ob->sputc('\n');
    }
}
using namespace IO;
int A,B,C,S;
const int Mod=49999;
struct Hash_Table
{
    int tot,last[Mod+50],nxt[Mod+50],val[Mod+50],id[Mod+50];
    inline void reset()
    {
        memset(last,0,sizeof(last));
        tot=0;
    }
    inline void insert(int v,int idx)
    {
        int pos=v%Mod;
        val[++tot]=v;
        nxt[tot]=last[pos];
        last[pos]=tot;
        id[tot]=idx;
    }
    inline int query(int v)
    {
        int pos=v%Mod;
        int ans=-1;
        for(pos=last[pos];pos;pos=nxt[pos])
        if(val[pos]==v)ans=max(ans,id[pos]);
        return ans;
    }
}task;
inline int gcd(int x,int y)
{
    return y?gcd(y,x%y):x;
}
inline void solve()
{
    task.reset();
    int res=1;
    for(int i=0;i<=40;i++)
    {
        if(res==B){W(i);return;}
        res=1ll*res*A%C;
    }
    res=1;int tmp=gcd(A,C),k=0;
    while(tmp!=1)
    {
        if(B%tmp){cout<<"No Solution"<<endl;return;}
        res=(1ll*res*A/tmp)%C;
        C/=tmp;B/=tmp;k++;
        tmp=gcd(A,C);
    }
    tmp=1;S=sqrt(double(C))+1;
    task.insert(B,0);
    for(int i=1;i<=S;i++)
    {
        tmp=1ll*tmp*A%C;
        task.insert(1ll*tmp*B%C,i);
    }
    int nowans=res;
    for(int i=1;i<=S;i++)
    {
        nowans=1ll*nowans*tmp%C;
        int t=task.query(nowans);
        if(t!=-1){W(i*S-t+k);return;}
    }
    cout<<"No Solution"<<endl;
}
int main()
{
    init();
    while(A=read(),C=read(),B=read(),(A||B||C))
    {
        A%=C;B%=C;
        solve();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值