【洛谷 P2485】 [SDOI2011]计算器 (BSGS)

题目链接
第一问:快速幂
第二问:扩欧解线性同余方程
第三问:\(BSGS\)
三个模板

#include <cstdio>
#include <cmath>
#include <map>
using namespace std;
typedef long long ll;
int a, b, p;
ll x, y, z;
ll exgcd(ll a, ll b, ll &x, ll &y){
    if(!b){
      x = 1; y = 0; return a;
    }
    ll d = exgcd(b, a % b, x, y);
    ll z = x; x = y; y = z - a / b * y;
    return d;
}
int fast_pow(int n, int k){  //n^k%p
    int ans = 1;
    while(k){
      if(k & 1) ans = (ll)ans * n % p;
      n = (ll)n * n % p;
      k >>= 1;
    }
    return ans;
}
ll BSGS(){   //a^x≡b(mod p)
    map <ll, ll> hash; hash.clear();
    int t = ceil(sqrt(p)), val = b, j = 1;
    for(int i = 0; i < t; ++i){
       hash[val] = i;
       val = (ll)val * a % p;
    }
    a = fast_pow(a, t);
    if(!a) return !b ? 1 : -1;
    for(int i = 0; i <= t; ++i){
       int k = hash.find(j) == hash.end() ? -1 : hash[j];
       if(k >= 0 && (i * t - k) >= 0) return (ll)i * t - k;
       j = (ll)j * a % p;
    }
    return -1;
}
int T, K;
int main(){
    scanf("%d%d", &T, &K);
    if(K == 3)
      while(T--){
        scanf("%d%d%d", &a, &b, &p);
        int ans = BSGS();
        ans == -1 ? puts("Orz, I cannot find x!") : printf("%d\n", ans);
      }
    else if(K == 1)
      while(T--){
        scanf("%d%d%d", &a, &b, &p);
        printf("%d\n", fast_pow(a, b));
      }
    else
      while(T--){
        scanf("%d%d%d", &a, &b, &p);
        if(b % (z = exgcd(a, p, x, y))) puts("Orz, I cannot find x!");
        else printf("%d\n", ((ll)x * b / z % p + p) % p);
      }
    return 0;
}

posted @ 2018-10-04 08:07  Qihoo360  阅读(159)  评论(0编辑  收藏  举报
You're powerful!