LUOGU P2485 [SDOI2011]计算器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40448823/article/details/81948465

传送门

解题思路

板子题,第一问快速幂,第二问求逆元,第三问bsgs

代码

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>

using namespace std;
typedef long long LL;

int y,z,p,T,k;
LL ans;
map<LL,int> mp;

inline LL fast_pow(LL x,int y){
    LL ret=1;
    for(;y;y>>=1){
        if(y&1) ret=ret*x%p;
        x=x*x%p;
    }
    return ret;
}

int main(){
    scanf("%d%d",&T,&k);
    if(k==1){
        while(T--){
            scanf("%d%d%d",&y,&z,&p);
            printf("%lld\n",fast_pow(1ll*y,z)%p);
        }
        return 0;
    }
    if(k==2){
        while(T--){
            scanf("%d%d%d",&y,&z,&p);z%=p;
            if(y%p==0) {puts("Orz, I cannot find x!");continue;}
            printf("%lld\n",(LL)z*fast_pow(1ll*y,p-2)%p);
        }
        return 0;
    }
    if(k==3){
        while(T--){
            mp.clear();
            scanf("%d%d%d",&y,&z,&p);z%=p;y%=p;
            if(y==0 && z!=0) {puts("Orz, I cannot find x!");continue;}
            int m=ceil(sqrt(p));
            LL now=z%p;mp[now]=0;
            for(register int i=1;i<=m;i++) {
                now=now*y%p;
                mp[now]=i;
            }
            now=1;bool flag=false;
            LL k=fast_pow(y,m);
            for(register int i=1;i<=m;i++){
                now=now*k%p;
                if(mp[now]){
                    ans=((LL)i*m-mp[now]+p)%p;
                    flag=1;
                    break;
                }
            }
            if(flag) printf("%lld\n",ans);
            else puts("Orz, I cannot find x!");
            ans=0;
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40448823/article/details/81948465