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

本文深入探讨了BSGS算法在解决特定数学方程ax≡bmodm中的应用。通过巧妙地将问题转化为易于处理的形式,文章详细介绍了如何利用BSGS算法高效求解该方程的解,特别适用于大规模数据集。算法的核心思想在于通过预处理和查找的方式,减少复杂度,提高计算效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 equationax≡bmodma^x\equiv b\quad mod\quad maxbmodmGiven 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)T(1T500), 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 &lt; m ≤ 109)(0 ≤ a, b &lt; m ≤ 10^9)(0a,b<m109).

Output
For each test case, print a single line containing an integer x(0 ≤ x ≤ 1017)x (0 ≤ x ≤ 10^{17})x(0x1017) 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算法。ax≡bmodma^x\equiv b\quad mod\quad maxbmodm其中x=i∗m−j,(j&lt;m)x=i*\sqrt{m}-j,(j&lt;\sqrt{m})x=imj(j<m),转化一下即变为ai∗m≡b∗ajmodma^{i*\sqrt{m}}\equiv b*a^j\quad mod\quad maimbajmodm我们只需枚举b∗ajb*a^jbaj并将其与jjj保存在map中,然后遍历ai∗ma^{i*\sqrt{m}}aim判断一下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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值