BZOJ 2242 快速幂 拓欧 BSGS

题意:快速幂、逆元、离散对数三合一。

码(17216K, 612ms)

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
template<class T> 
inline void read(T& x)
{
    char c = getchar(); T p = 1, n = 0;
    while(c < '0' || c > '9'){if(c == '-') p = -1; c = getchar();}
    while(c >= '0' && c <= '9'){n = n * 10 + c - '0'; c = getchar();}
    x = p * n;
}
template<class T, class U>
inline void read(T& x, U& y){read(x), read(y);}
template<class T, class U, class V>
inline void read(T& x, U& y, V& z){read(x), read(y), read(z);}
const int hashmod = 1 << 20;
class HashTable
{
private:
    int hash[hashmod + 10], stack[1 << 20], stacktop;
    long long value[hashmod + 10];
    int locate(int x)
    {
        int h = x % hashmod;
        while(hash[h] != -1 && hash[h] != x) h++, h %= hashmod;
        return h;
    }
public:
    HashTable() : stacktop(0){memset(hash, -1, sizeof hash);}
    void insert(int x, long long v)
    {
        int h = locate(x);
        if(hash[h] == -1)
            hash[h] = x, value[h] = v, stack[stacktop++] = h;
    }
    long long get(int x)
    {
        int h = locate(x);
        return hash[h] != -1 ? value[h] : -1;
    }
    void clear(){while(stacktop)hash[stack[--stacktop]] = -1;}
} hash;
long long power(long long a, long long b, long long p)
{
    long long ret = 1;
    for(; b; b >>= 1, a *= a, a %= p)
        if(b & 1)
            ret *= a, ret %= p;
    return ret;
}
void gcd(long long a, long long b, long long &d, long long &x, long long &y)
{
    if(b == 0)
        d = a, x = 1, y = 0;
    else
        gcd(b, a % b, d, y, x), y -= (a / b) * x;
}
template<class T>
T bsgs(T a, T b, T c)
{
    if(!a && !b) return 1;
    if(!a) return -1;
    T sqrtC = ceil(sqrt(c));
    T base = 1;
    hash.clear();
    for(int i = 0; i < sqrtC; i++, base *= a, base %= c)
        hash.insert(base, i);
    T inv = power(a, c - 1 - sqrtC, c);
    for(T i = 0, invD = 1, j; i < sqrtC; i++, invD *= inv, invD %= c)
        if((j = hash.get(b * invD % c)) != -1)
            return i * sqrtC + j;
    return -1; 
}
int main()
{
    int t, k; read(t, k);
    while(t--)
    {
        long long y, z, p; read(y, z, p);
        y %= p;
        if(k == 1)
            printf("%d\n", power(y, z, p));
        else if(k == 2)
        {
            long long d, x, yy;
            gcd(y, p, d, x, yy);
            if(z % d)
                puts("Orz, I cannot find x!");
            else
            {
                y /= d, z /= d, p /= d;
                gcd(y, p, d, x, yy);
                printf("%lld\n", (x + p) % p * z % p);
            }
        }
        else
        {
            long long x = bsgs(y, z, p);
            if(x == -1)
                puts("Orz, I cannot find x!");
            else
                printf("%lld\n", x);
        }
    }
    return 0;
}

标签: 快速幂, 逆元, 拓欧, bsgs

仅有一条评论

  1. wwwzbwcom wwwzbwcom

    再来看一次神犇的求逆元

添加新评论