题解P4454 [CQOI2018]破解D-H协议
作者:互联网
题面比较长,但其实就是一道板子题
根据题意, \(g^a\equiv A(mod~p),g^b\equiv B(mod~p)\),可以直接通过BSGS求出 \(a,b\) 的值,然后直接用快速幂算出来即可
关于BSGS,可以看看我的博客
代码
#include<iostream>
#include<cmath>
#include<unordered_map>
using namespace std;
typedef long long ll;
int ksm(int a, int b, int p)
{
int res = 1;
while (b)
{
if (b & 1)
res = (ll)res * a % p;
a = (ll)a * a % p;
b >>= 1;
}
return res;
}
int BSGS(int a, int b, int p)
{
if (1 % p == b % p)
return 0;
unordered_map<int, int> hash;
int k = sqrt(p) + 1;
for (int i = 0, j = b % p; i < k; i++, j = (ll)j * a % p)
hash[j] = i;
int ak = ksm(a, k, p);
for (int i = 1, j = ak; i <= k; i++, j = (ll)j * ak % p)
if (hash.count(j))
return i * k - hash[j];
return -1;
}
int main()
{
int g, p;
scanf("%d%d", &g, &p);
int n;
scanf("%d", &n);
while (n--)
{
int A, B;
scanf("%d%d", &A, &B);
int a = BSGS(g, A, p);
int b = BSGS(g, B, p);
printf("%d\n", ksm(g, (ll)a * b % (p - 1), p));
}
return 0;
}
标签:P4454,int,题解,ll,CQOI2018,res,include,ak,BSGS 来源: https://www.cnblogs.com/A2484337545/p/14695479.html