[CQOI2018] 破解D-H协议

题目描述:

求密钥哇.

题目分析:

K=Ba K = B a
gaA(modp) g a ≡ A ( mod p )
现在我们需要求解出a,上面的那个式子很明显就是BSGS的形式,套用BSGS即可求出
预处理 gi g i 的值,用map存一下

题目链接:

Luogu 4454
BZOJ 5296

Ac 代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <map>
#include <cmath>
#define ll long long
std::map<ll,ll> a;
ll mod,g,m;
int t;
inline void init()
{
    ll x=1;
    a[1]=0;
    for(ll i=1;i<=m;i++)
    {
        x=(x*g)%mod;
        a[x]=i;
    }
} 
inline void exgcd(ll a,ll b,ll &d,ll &x,ll &y)
{
    if(!b) d=a,x=1,y=0;
    else exgcd(b,a%b,d,y,x),y-=x*(a/b);
}
inline ll inv(ll x)
{
    ll d,xx,y;
    exgcd(x,mod,d,xx,y);
    return d==1?(xx+mod)%mod:-1;
}
inline ll fastpow(ll x,ll y)
{
    ll ans=1;
    for(;y;y>>=1,x=(x*x)%mod)
     if(y&1) ans=(ans*x)%mod;
    return ans;
}
inline ll BSGS(ll x)
{
    for(ll i=0;i<=m;i++)
    {
        ll val=(x*inv(fastpow(g,i*m)))%mod;
        if(a.count(val)) return i*m+a[val];
    }
    return -1;
}
int main()
{
    scanf("%lld%lld",&g,&mod);
    m=std::ceil(sqrt(mod));
    init();
    scanf("%d",&t);
    for(int i=1;i<=t;i++)
    {
        ll A,B;
        scanf("%lld%lld",&A,&B);
        printf("%lld\n",fastpow(B,BSGS(A)));
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值