Bzoj3239:Discrete Logging:BSGS模板题

2 篇文章 0 订阅

题目链接3239:Discrete Logging

裸BSGS,终于会写了QAQ

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
using namespace std;
const int maxn=1500010;
const int mod=99997;
LL p,b,c,ans;
bool flag;

struct hashmap{
	int next[maxn],tot;
	LL val[maxn];
	int h[mod],As[maxn];
	void push(LL x,int id){
		int now=x%mod; if (now<0) now+=mod;
		for (int i=h[now];i;i=next[i])
		    if (val[i]==x) return;
		++tot; next[tot]=h[now]; h[now]=tot;
		val[tot]=x; As[tot]=id; return;
	}
	int find(LL x){
		int now=x%mod; if (now<0) now+=mod;
		for (int i=h[now];i;i=next[i])
		    if (val[i]==x) return As[i];
		return -1;
	}
	void init(){
		memset(h,0,sizeof(h)); tot=0;
	}
}s;

void exgcd(LL D,LL p,LL &x,LL &y){
	LL t;
	if(!p){x=1;y=0;return;}
	exgcd(p,D%p,x,y);
	t=x; x=y; y=t-D/p*y;
}

int main(){
	while (~scanf("%lld%lld%lld",&p,&b,&c)){
		s.init();
		int m=ceil(sqrt(p));
		LL last=1; s.push(1,0);
		for (int i=1;i<m;++i){
			LL x=(last*b%p+p)%p;
			s.push(x,i); last=x;
		}
		LL x,y;
		exgcd(1,p,x,y);
		x=(x*c%p+p)%p;
		if (s.find(x)!=-1)
			{ans=0*m+s.find(x);printf("%lld\n",ans);continue;}
		LL D=last*b%p,tmp=D;
		flag=0;
		for (int i=1;i<=m;++i){
			exgcd(D,p,x,y);
			x=(x*c%p+p)%p;
			if (s.find(x)!=-1)
				{ans=i*m+s.find(x);printf("%lld\n",ans);flag=1;break;}
			D=(D*tmp%p+p)%p;
		}
		if (!flag) printf("no solution\n");
	}
}


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值