比赛 2025新春开学欢乐赛 评测结果 AATMMTMMMM
题目名称 t2 最终得分 20
用户昵称 健康铀 运行时间 8.335 s
代码语言 C++ 内存使用 426.68 MiB
提交时间 2025-02-15 17:39:34
显示代码纯文本
#include <bits/stdc++.h>

using namespace std;

struct Edge {
    int u, v;
    long long w;
    bool operator<(const Edge& other) const {
        return w < other.w;
    }
};

class UnionFind {
public:
    UnionFind(int n) : parent(n), rank(n, 0) {
        iota(parent.begin(), parent.end(), 0);
    }

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

    void unite(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);
        if (rootX != rootY) {
            if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else {
                parent[rootY] = rootX;
                if (rank[rootX] == rank[rootY]) {
                    rank[rootX]++;
                }
            }
        }
    }

private:
    vector<int> parent;
    vector<int> rank;
};

long long kruskal(int n, vector<Edge>& edges) {
    UnionFind uf(n);
    long long mstWeight = 0;
    int edgesUsed = 0;

    for (const auto& edge : edges) {
        int u = edge.u;
        int v = edge.v;
        long long w = edge.w;
        if (uf.find(u) != uf.find(v)) {
            uf.unite(u, v);
            mstWeight += w;
            edgesUsed++;
            if (edgesUsed == n - 1) {
                break;
            }
        }
    }

    return mstWeight;
}

int main() {
		freopen("emptyfist.in","r",stdin);
			freopen("emptyfist.out","w",stdout);
    int n1, n2, m1, m2;
    cin >> n1 >> n2 >> m1 >> m2;

    vector<Edge> edges;
    for (int i = 0; i < m1; ++i) {
        int u, v;
        long long w;
        cin >> u >> v >> w;
        --u; --v; 
        for (int i = 0; i < n2; ++i) {
            edges.push_back({u * n2 + i, v * n2 + i, w});
        }
    }
    for (int i = 0; i < m2; ++i) {
        int u, v;
        long long w;
        cin >> u >> v >> w;
        --u; --v;
        for (int i = 0; i < n1; ++i) {
            edges.push_back({i * n2 + u, i * n2 + v, w});
        }
    }
    sort(edges.begin(), edges.end());
    long long result = kruskal(n1 * n2, edges);

    cout << result << endl;

    return 0;
}