• 【BZOJ2242】[SDOI2011]计算器 BSGS


    【BZOJ2242】[SDOI2011]计算器

    Description

    你被要求设计一个计算器完成以下三项任务:
    1、给定y,z,p,计算Y^Z Mod P 的值;
    2、给定y,z,p,计算满足xy≡ Z ( mod P )的最小非负整数;
    3、给定y,z,p,计算满足Y^x ≡ Z ( mod P)的最小非负整数。

    Input

     输入包含多组数据。

    第一行包含两个正整数T,K分别表示数据组数和询问类型(对于一个测试点内的所有数据,询问类型相同)。
    以下行每行包含三个正整数y,z,p,描述一个询问。

    Output

    对于每个询问,输出一行答案。对于询问类型2和3,如果不存在满足条件的,则输出“Orz, I cannot find x!”,注意逗号与“I”之间有一个空格。

    Sample Input

    【样例输入1】
    3 1
    2 1 3
    2 2 3
    2 3 3
    【样例输入2】
    3 2
    2 1 3
    2 2 3
    2 3 3
    【数据规模和约定】
    对于100%的数据,1<=y,z,p<=10^9,为质数,1<=T<=10。

    Sample Output

    【样例输出1】
    2
    1
    2
    【样例输出2】
    2
    1
    0

    题解:第一问快速幂,第二问exgcd,第三问bsgs(又名拔山盖世算法)

    BSGS算法用来处理ax=b(mod p,p是质数)的问题,先将x换成i*m-j,其中m是sqrt(p)上取整,那么ai*m-j=b(mod p)=> ai*m=baj(mod p),那么先从0到m枚举j,将baj存入hash表中,在从1-m枚举i,在hash表里查找ai,第一个找到的就是最小整数解

     

    #include <cstdio>
    #include <cstring>
    #include <iostream>
    #include <map>
    #include <cmath>
    using namespace std;
    typedef long long ll;
    ll P,m;
    map<ll,int>	mp;
    ll pm(ll x,ll y)
    {
    	ll z=1;
    	while(y)
    	{
    		if(y&1)	z=z*x%P;
    		x=x*x%P,y>>=1;
    	}
    	return z;
    }
    ll exgcd(ll a,ll b,ll &x,ll &y)
    {
    	if(b==0)	{x=1,y=0;	return a;}
    	ll tmp=exgcd(b,a%b,x,y),t=x;
    	x=y,y=t-a/b*x;
    	return tmp;
    }
    int main()
    {
    	int T,K;
    	ll i;
    	scanf("%d%d",&T,&K);
    	while(T--)
    	{
    		ll A,B,g,x,y;
    		scanf("%lld%lld%lld",&A,&B,&P);
    		if(K==1)	printf("%lld
    ",pm(A,B));
    		else	if(K==2)
    		{
    			P=-P;
    			g=exgcd(A,P,x,y);
    			if(B%g)
    			{
    				printf("Orz, I cannot find x!
    ");
    				continue;
    			}
    			P/=g,x=x*B/g%P;
    			if(x<0)	x=(x%P+P)%P;
    			printf("%lld
    ",x);
    		}
    		else
    		{
    			if(A%P==0)
    			{
    				printf("Orz, I cannot find x!
    ");
    				continue;
    			}
    			mp.clear();
    			m=ceil(sqrt(1.0*P));
    			for(x=1,i=0;i<=m;i++)	mp[x*B%P]=i,x=x*A%P;
    			for(y=x=pm(A,m),i=1;i<=m;i++)
    			{
    				if(mp.find(y)!=mp.end())
    				{
    					printf("%d
    ",i*m-mp[y]);
    					break;
    				}
    				y=y*x%P;
    			}
    			if(i==m+1)	printf("Orz, I cannot find x!
    ");
    		}
    	}
    	return 0;
    }

     

  • 相关阅读:
    iOS 最新版 CocoaPods 的安装流程
    AFNetworking 3.0.4 的使用
    NSPredicate谓词
    PHP基本类型操作
    MJExtension使用指导(转)
    字典转模型KVC和runtime二者实现与区别
    iOS之KVC字典转模型的底层实现
    runtime 总结(原创)
    Objective-C Runtime能做什么?
    Runtime那些事儿(消息机制)
  • 原文地址:https://www.cnblogs.com/CQzhangyu/p/6999258.html
Copyright © 2020-2023  润新知