最小生成树的模板题
不多说,可以看我之前写的最小生成树的博客
#include <bits/stdc++.h> using namespace std; const int maxn = 1e6 + 10; int pre[maxn]; struct node { int u, v, e; bool operator<(const node x) { return e < x.e; } } w[maxn]; int find(int x) { return pre[x] == x ? x : pre[x] = find(pre[x]); } void join(int x, int y) { pre[find(x)] = find(y); } int main() { int n, m, ans = 0, sum; scanf("%d%d%d", &sum, &n, &m); for (int i = 1; i <= m; ++i) pre[i] = i; for (int i = 1; i <= n; ++i) scanf("%d%d%d", &w[i].u, &w[i].v, &w[i].e); sort(w + 1, w + n + 1); for (int i = 1; i <= n; ++i) { if (find(w[i].u) != find(w[i].v)) { join(w[i].u, w[i].v); ans += w[i].e; } } if (ans <= sum) printf("Yes\n"); else printf("No\n"); }