Bzoj 3122 离散对数

版权声明:By MrBird https://blog.csdn.net/MrBird_to_fly/article/details/82778579

题目描述
在这里插入图片描述

HINT
这题的p是素数。。。尼玛想半天不会。。。会合数版本的请联系我

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
map<ll,int>mp;
void exgcd(ll a, ll b, ll &x, ll &y){
	if(b==0){
		x=1, y=0;
		return ;
	}
	exgcd(b, a%b, x, y);
	ll tmp=x;
	x=y;
	y=tmp-(a/b)*y;
}
ll bsgs(ll d,ll a,ll b,ll c){
	mp.clear();
	ll m=sqrt(c)+1;
	ll mul=1;
	for(int j=1;j<=m;j++){
		mul=mul*a%c;
		mp[mul*b%c]=j;
	}
	for(int i=1;i<=m;i++){
		d=d*mul%c;
		if(mp.find(d)!=mp.end()){
			return i*m-mp[d];
		}
	}
	return -2;//无解+1后等于-1
}
int main(){
	int T;
	scanf("%d",&T);
	ll p,a,b,x,t;
	while(T--){
		scanf("%lld%lld%lld%lld%lld",&p,&a,&b,&x,&t);
		if(x==t)printf("1\n");
		else {
			if(a==0){
				if(b==t)printf("2\n");
				else printf("-1\n");
			}
			else if(a==1){
				if(b==0){
					printf("-1\n");
				}
				else {
					t=(t-x+p)%p;
					ll g=__gcd(b,p);
					if(t%g)printf("-1\n");
					else {
						b/=g,t/=g,p/=g;
						ll x,y;
						exgcd(b,p,x,y);
						x=x*t%p;
						if(x<0)x+=p;
						printf("%lld\n",x+1);
					}
				}
			}
			else {
				ll d=((a-1)*x+b)%p;
				b=((a-1)*t+b)%p;
				printf("%lld\n",bsgs(d,a,b,p)+1);
			}
		}
	}
}

猜你喜欢

转载自blog.csdn.net/MrBird_to_fly/article/details/82778579
今日推荐