bzoj2242 [SDOI2011]计算器 exgcd+ksm+bsgs

三个板子,注意bsgs的时候要特判无解,即a%p==0||b%p==0(bsgs还是很巧妙的。。)


码:

#include<iostream>
#include<cstdio>
#include<map>
#include<cmath>
using namespace std;
#define ll long long
map<ll,bool>ma;
map<ll,int>dui;
ll a,b,p,ans,x,y,i,j; 
int T,k;
ll ksm(ll a,ll b)
{ll ans=1;
while(b)
{
if(b&1)ans=ans*a%p;
b/=2;
a=a*a%p;
}	
	return ans;
}
void exgcd(ll a,ll b)
{
	if(!b)
	{
		y=0;
		x=1;
		ans=a;
		return ;
	}
	exgcd(b,a%b);
	ll t=x;
	x=y;
	y=t-a/b*y;	
}
int main()
{
	scanf("%d%d",&T,&k);
	while(T--)
	{
		scanf("%lld%lld%lld",&a,&b,&p);	
	if(k==1)
	{	
	printf("%lld\n",ksm(a,b));		
	}	
	if(k==2)	
	{
	exgcd(a,p);
	x=(x+p)%p;	
		if(b%ans==0)
		{
			printf("%lld\n",x*(b/ans)%p);
		}else printf("Orz, I cannot find x!\n");
	}
	if(k==3)
	{
		if(b%p==0||a%p==0)
			{
			printf("Orz, I cannot find x!\n");
		continue;
		}
	ll o=sqrt(p);
	ma.clear();
	dui.clear();
		for(i=0;i<=o;i++)
		{
			ma[ksm(a,i)]=1;	
			dui[ksm(a,i)]=i;
		}
		bool yj=0;
		for(i=0;i<=o;i++)
		{
			exgcd(ksm(a,i*o),p);
			if(ma[(b*(x+p)%p+p)%p])
			{
				printf("%lld\n",i*o+dui[(b*(x+p)%p+p)%p]);
				yj=1;break;
			}
		}
		if(yj==0)
		{
			printf("Orz, I cannot find x!\n");
		}
	}	
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值