bzoj2242: [SDOI2011]计算器

模版大杂烩系列

第一问是快速幂

第二问拓展欧几里得

第三问BSGS

#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<map>
using namespace std;
typedef long long LL;

LL quick_pow(LL A,LL p,LL mod)
{
    LL ret=1;
    while(p!=0)
    {
        if(p%2==1)ret=(ret*A)%mod;
        A=(A*A)%mod;p/=2;
    }
    return ret;
}
void solve1(int T)
{
    while(T--)
    {
        LL y,z,p;
        scanf("%lld%lld%lld",&y,&z,&p);
        printf("%lld\n",quick_pow(y,z,p));
    }
}

//--------------------------------------

LL exgcd(LL a,LL b,LL &x,LL &y)
{
    if(a==0)
    {
        x=0,y=1;
        return b;
    }
    else
    {
        LL tx,ty;
        LL d=exgcd(b%a,a,tx,ty);
        x=ty-b/a*tx;
        y=tx;
        return d;
    }
}
void solve2(int T)
{
    while(T--)
    {
        LL yy,z,p;
        scanf("%lld%lld%lld",&yy,&z,&p);
        
        LL A=yy,B=p,K=z,x,y;
        LL d=exgcd(A,B,x,y);
        if(K%d!=0)printf("Orz, I cannot find x!\n");
        else
        {
            x=(x*(K/d)%(B/d)+(B/d))%(B/d);
            printf("%lld\n",x);
        }
    }
}

//----------------------------------------

map<LL,LL>Hash;
LL BSGS(LL a,LL b,LL mod)
{
    Hash.clear();b%=mod;
    
    LL t=(LL(sqrt(double(mod+1)))),k=1;
    for(int j=0;j<t;j++)
    {
        Hash[b*k%mod]=j;//b*a^j
        k=(k*a)%mod;
    }
    
    a=quick_pow(a,t,mod);//a^t
    if(a==0)return b==0?1:-1;
    else
    {
        LL k=1;
        for(int i=0;i<=t;i++)
        {
            if(Hash.find(k)!=Hash.end())
            {
                LL j=Hash[k];
                if(t*i-j>=0)return t*i-j;
            }
            k=(k*a)%mod;
        }
        return -1;
    }
}
void solve3(int T)
{
    while(T--)
    {
        LL y,z,p;
        scanf("%lld%lld%lld",&y,&z,&p);
        if(y%p==0)printf("Orz, I cannot find x!\n");
        else
        {
            LL d=BSGS(y,z,p);
            if(d==-1)printf("Orz, I cannot find x!\n");
            else printf("%lld\n",d);
        } 
    }
}

int main()
{
    int T,K;
    scanf("%d%d",&T,&K);
         if(K==1)solve1(T);
    else if(K==2)solve2(T);
    else if(K==3)solve3(T);
    
    return 0;
}

 

转载于:https://www.cnblogs.com/AKCqhzdy/p/9322418.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值