Codeforces-gym/101853G:Hard Equation(BSGS)

版权声明:http://blog.csdn.net/Mitsuha_。 https://blog.csdn.net/Mitsuha_/article/details/87368655

G. Hard Equation
time limit per test 10.0 s
memory limit per test 256 MB
inputs tandard input
outputs tandard output
Consider the following equation a x b m o d m a^x\equiv b\quad mod\quad m Given a, b and m, your task is to find a value x that satisfy the equation for the given values. Can you?

Input
The first line contains an integer T ( 1 T 500 ) T (1 ≤ T ≤ 500) , in which T is the number of test cases.

Each test case consists of a line containing three integers a, b and m ( 0 a , b < m 1 0 9 ) (0 ≤ a, b < m ≤ 10^9) .

Output
For each test case, print a single line containing an integer x ( 0 x 1 0 17 ) x (0 ≤ x ≤ 10^{17}) that satisfy the equation , for the given a, b and m.

If there are multiple solutions, print any of them. It is guaranteed that an answer always exist for the given input.

Example
input
3
3 9 11
2 3 5
2 1 5
output
2
3
4

思路:BSGS算法。 a x b m o d m a^x\equiv b\quad mod\quad m 其中 x = i m j ( j < m ) x=i*\sqrt{m}-j,(j<\sqrt{m}) ,转化一下即变为 a i m b a j m o d m a^{i*\sqrt{m}}\equiv b*a^j\quad mod\quad m 我们只需枚举 b a j b*a^j 并将其与 j j 保存在map中,然后遍历 a i m a^{i*\sqrt{m}} 判断一下map里是否有对应的值即可。

#include<bits/stdc++.h>
using namespace std;
const int MAX=5e5+10;
typedef long long ll;
ll BSGS(ll a,ll b,ll m)
{
    a%=m;
    b%=m;
    if(b==1)return 0;
    unordered_map<ll,ll>ma;
    ll n=sqrt(2*m)+1;
    ll e=1;
    for(int i=0;i<n;i++)
    {
        if(ma.count(b*e%m)==0)ma[b*e%m]=i;//很奇怪去掉ma.count(b*e%m)==0就会WA
        e=e*a%m;
    }
    ll t=1;
    for(int i=1;i<=n+1;i++)
    {
        t=t*e%m;
        if(ma.count(t))return i*n-ma[t];
    }
    return -1;
}
int main()
{
    int T;
    cin>>T;
    while(T--)
    {
        ll a,b,m;
        scanf("%lld%lld%lld",&a,&b,&m);
        printf("%lld\n",BSGS(a,b,m));
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Mitsuha_/article/details/87368655