POJ2417 - Discrete Logging

2017/02/26

本来是要做 SDOI2011 的计算器的,但是写好交上去狂 WA 不止。

垃圾 BZOJ 毁我青春(然而是我又蒟又非)

题目

求解离散对数,输入 p, y, z 求 y^x == z mod p 的最小非负 x

样例输入:

5 2 1
5 2 2
5 2 3
5 2 4
5 3 1
5 3 2
5 3 3
5 3 4
5 4 1
5 4 2
5 4 3
5 4 4
12345701 2 1111111
1111111121 65537 1111111111

样例输出:

0
1
3
2
0
3
1
2
0
no solution
no solution
1
9584351
462803587

代码

此题卡 map ,考虑到 POJ 也没有 unordered_maptr1/unordered_maphash_map ,所以说要自己写一个。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
using namespace std;
typedef long long LL;

namespace hash_map {
    const int BKT_SIZ = 1 << 16;
    const int BKT_MSK = BKT_SIZ - 1;
    const int POL_SIZ = 5E5;

    int good_hash(LL a) {
        return (a * 2654435761) & 0xFFFFFFFF;
    }

    struct node {
        LL k; int v;
        node* nxt;
    } POOL[POL_SIZ]; int ppos;
    node* Head[BKT_SIZ];

    void add(LL k, int v) {
        int kk = good_hash(k) & BKT_MSK;
        node *cur = Head[kk];
        while(cur && cur->k != k) {
            cur = cur->nxt;
        }

        if(cur) cur->v = v;
        else {
            POOL[ppos].nxt = Head[kk];
            Head[kk] = &POOL[ppos++];
            Head[kk]->k = k, Head[kk]->v = v;
        }
    }

    int check(LL k) {
        int kk = good_hash(k) & BKT_MSK;
        node* cur = Head[kk];
        while(cur && cur->k != k) {
            cur = cur->nxt;
        }
        if(cur) return cur->v;
        return -1;
    }

    void restore() {
        ppos = 0;
        memset(POOL, 0, sizeof(POOL));
        memset(Head, 0, sizeof(Head));
    }
};

LL fastpow(LL y, LL z, LL p) {
    LL c = z;
    LL ret = 1, cur = y % p;
    while(c) {
        if(c & 1) ret = (ret * cur) % p;
        cur = (cur * cur) % p;
        c >>= 1;
    }
    return ret;
}

LL y, z, p;
void case3() {  // Pure BSGS, calc discrete logarithm
                // Find such x, s.t. y^x == z mod p
    y %= p;
    if(!y && !z) { printf("1\n"); return; }
    if(!y) { printf("no solution\n"); return; }
    LL m = LL(ceil(sqrt(p)));
    for(int i=0, cyj=z%p;i<=m;i++) {
        hash_map :: add(cyj, i);
        cyj = (cyj * y) % p;
    }

    LL ym = fastpow(y, m, p);
    for(int i=1, cym=ym;i<=m;i++) {
        int val;
        if((val = hash_map :: check(cym)) != -1) {
            printf("%lld\n", i * m - val);
            return;
        }
        cym = (cym * ym) % p;
    }

    printf("no solution\n");
}

int main() {
    while(scanf("%lld %lld %lld", &p, &y, &z) != EOF) {
        hash_map :: restore();
        case3();
    }
}