多次询问两个数的公共质因子

例题链接

牛客小白月赛60:E-寻找小竹!

思路

两个数的公共质因子也是它们的 gcd 的质因子,因此在素数筛的过程中顺便记录每个数 $x$ 的最小质因子,记为 $mnp[x]$,对于输入的两个数 $a_x$ 和 $a_y$ ,记 $g=gcd(a_x,a_y)$,不断用 $mnp[g]$ 除 $g$ 直到 $g$ 为 $1$,在这个过程中可以统计质因子,并且是 $log$ 级别的时间复杂度。

回到牛客的这道题,只需要对每条边的顶点权值检查公共质因子的个数是否大于等于 $2$,然后用并查集维护连通块大小即可。

代码

 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
#include "iostream"
#include "vector"
#include "string"
#include "utility"
#include "queue"
#include "set"
#include "map"
#include "unordered_map"
#include "algorithm"
#include "cstring"
#include "stack"
#include "cmath"
#include "numeric"
#include "cassert"

using namespace std;

typedef long long ll;
const int N = 1e6 + 7;
const int M = 5e6 + 7;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll MOD = 1e9 + 7;
int fa[N], n, a[N], mnp[M], prime[M], sz[N];

void init() {
    for (int i = 0; i < N; i++) {
        fa[i] = i;
        sz[i] = 1;
    }

    memset(prime, true, sizeof(prime));
    for (int i = 2; i < M; i++) {
        if (!prime[i])
            continue;
        mnp[i] = i;
        for (ll j = 1LL * i * i; j < M; j += i) {
            prime[j] = false;
            mnp[j] = i;
        }
    }
}

int find(int x) {
    if (x != fa[x])
        fa[x] = find(fa[x]);
    return fa[x];
}

void unionSet(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y)
        return;
    fa[x] = y;
    sz[y] += sz[x];
}

bool check(int x, int y) {
    int g = gcd(x, y), cnt = 0;
    while (g != 1) {
        cnt++;
        int cur = mnp[g];
        assert(cur > 0);
        while (g % cur == 0)
            g /= cur;
    }
    return cnt >= 2;
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    init();
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> a[i];
    for (int i = 0; i < n - 1; i++) {
        int x, y;
        cin >> x >> y;
        if (check(a[x], a[y]))
            unionSet(x, y);
    }

    int ans = 0;
    for (int i = 1; i <= n; i++) {
        ans = max(ans, sz[find(i)]);
    }
    cout << ans;

    return 0;
}
updatedupdated2022-11-122022-11-12