跳到正文

题解

题解:P11867 大家的公因数 2

庙朝大海约 6 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年5月7日
篇幅
约 6 分钟
题目
P11867

版本

  1. v1当前

并查集

利用并查集将每个数字和他的因子合并,构建出几个连通块。

线性基

求出每个连通块的异或线性基,通过异或线性基的异或操作判断是否存在满足条件的路径。 异或线性基

C++
#include <bits/stdc++.h>
using namespace std;
int n;
int a[500050];
int b[500050];
int vm[10000010];


vector<int> ps;

void InitPs(int c) {
    int v = sqrt(c) + 1;
    vector<bool> isp(v + 1, true);
    for (int i = 2; i <= v; i++) {
        if (isp[i]) {
            ps.push_back(i);
            for (int j = i * i; j <= v; j += i) {
                isp[j] = false;
            }
        }
    }
}

struct Dsu {
    int fa[10000010];

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

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

    void merge(int x, int y) {
        int fx = find(x);
        int fy = find(y);
        if (fx != fy) {
            fa[fx] = fy;
        }
    }

    bool same(int x, int y) {
        return find(x) == find(y);
    }
};

Dsu dsu;

struct Node {
    int p[25];
};

unordered_map<int, Node> mp;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    // freopen("in.in", "r", stdin);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }

    for (int i = 1; i <= n; i++) {
        cin >> b[i];
    }

    InitPs(10000000);
    dsu.init(10000000);

    vector<int> fs;
    for (int i = 1; i <= n; i++) {
        int x = a[i];
        fs.clear();
        for (int j = 0; j < ps.size() && ps[j] * ps[j] <= x; j++) {
            int p = ps[j];
            if (x % p == 0) {
                fs.push_back(p);
                while (x % p == 0) {
                    x /= p;
                }
            }
        }
        if (x > 1) {
            fs.push_back(x);
        }

        for (int j = 0; j < fs.size(); j++) {
            dsu.merge(fs[j], a[i]);
        }
    }

    for (int i = 1; i <= n; i++) {
        Node& node = mp[dsu.find(a[i])];
        int x = b[i];
        for (int j = 24; ~j; j--) {
            if (!(x >> j)) {
                continue;
            }
            if (node.p[j] == 0) {
                node.p[j] = x;
                break;
            }
            x ^= node.p[j];
        }
    }

    int q;
    cin >> q;
    while (q--) {
        int u, v, w;
        cin >> u >> v >> w;

        if (dsu.same(u, v)) {
            Node& node = mp[dsu.find(u)];
            for (int j = 24; ~j && w; j--) {
                if (!(w >> j)) {
                    continue;
                }
                w = w ^ node.p[j];
            }
            if (w == 0) {
                cout << "Yes" << '\n';
            }
            else {
                cout << "No" << '\n';
            }
        }
        else {
            cout << "No" << '\n';
        }
    }


    return 0;
}
原文