Hard Equation Gym - 101853G

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_39132605/article/details/100581498

https://cn.vjudge.net/problem/Gym-101853G 

#include <iostream>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <set>
#include <map>
#include <stack>
//#include <tr1/unordered_map>
//#include <unordered_map>
#include <cmath>
//#include<bits/stdc++.h>
using namespace std;

#define sfi(i) scanf("%d",&i)
#define sfl(i) scanf("%I64d",&i)
#define sfs(i) scanf("%s",(i))
#define pri(i) printf("%d\n",i)
#define prl(i) printf("%I64d\n",i)
#define sff(i) scanf("%lf",&i)
#define ll long long
#define ull unsigned long long
#define uint unsigned int
#define mem(x,y) memset(x,y,sizeof(x))
#define INF 0x3f3f3f3f
#define inf 1e18
#define eps 1e-10
#define PI acos(-1.0)
#define lowbit(x) ((x)&(-x))
#define fl() printf("flag\n")
#define MOD(x) ((x%mod)+mod)%mod
#define endl '\n'
#define pb push_back
#define lson (rt<<1)
#define rson (rt<<1|1)
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)

template<typename T>inline void read(T &x)
{
    x=0;
    static int p;p=1;
    static char c;c=getchar();
    while(!isdigit(c)){if(c=='-')p=-1;c=getchar();}
    while(isdigit(c)) {x=(x<<1)+(x<<3)+(c-48);c=getchar();}
    x*=p;
}

//-----------------------------------------------

const int maxn=1e6+9;
const int maxm=3e6+9;
const int mod=99991;

ll head[maxn];
ll tot;
ll hs[maxn],id[maxn];
ll nex[maxn];
void init()
{
    tot=0;
    mem(head,-1);
}

void add(ll x,ll i)
{
    hs[tot]=x;
    id[tot]=i;
    ll u=x%mod;
    nex[tot]=head[u];
    head[u]=tot++;
}

ll query(ll x)
{
    ll u=x%mod;
    for(int i=head[u];i!=-1;i=nex[i])
    {
        if(hs[i]==x) return id[i];
    }
    return -1;
}


//a^x=b(mod c)
ll BSGS(ll a,ll b,ll c)
{
    a%=c;
    b%=c;
    if(b==1) return 0;
    ll g=1,d=1,k=0;
    while((g=__gcd(a,c))!=1)
    {
        if(b%g) return -1;
        b/=g;
        c/=g;
        k++;
        d=d*(a/g)%c;
        if(b==d) return k;
    }

    ll m=ceil(sqrt(c*1.0)),q=1;
    for(ll i=0;i<m;i++)
    {
        add(q*b%c,i);
        q=q*a%c;
    }
    for(ll i=1;i<=m+1;i++)
    {
        d=d*q%c;
        ll j=query(d);
        if(j!=-1) return i*m-j+k;
    }
    return -1;
}

int main()
{
    //FAST_IO;
    //freopen("input.txt","r",stdin);


    int T;
    sfi(T);
    while(T--)
    {
        init();
        ll a,b,m;
        scanf("%lld%lld%lld",&a,&b,&m);
        ll ans=-1;
        ans=BSGS(a,b,m);
        printf("%lld\n",ans);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_39132605/article/details/100581498