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
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
, in which T is the number of test cases.
Each test case consists of a line containing three integers a, b and m .
Output
For each test case, print a single line containing an integer
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算法。 其中 ,转化一下即变为 我们只需枚举 并将其与 保存在map中,然后遍历 判断一下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;
}