P2121 拆地毯【kruskal】
题目
https://www.luogu.com.cn/problem/P2121
分析
组织者被要求只能保留 K 条地毯,且保留的地毯构成的图中,任意可互相到达的两点间只能有一种方式互相到达:
要构成只有K条边的最大生成树——使用kruskal
代码
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> using namespace std; #define maxn 100002 #define maxm 100002 struct node { int from; int to; int dis; }e[maxm*2]; int n, m, k; int father[maxn]; bool cmp(struct node &a, struct node &b) { return a.dis > b.dis; } int find(int x) { if (father[x] == x)return x; return father[x] = find(father[x]); } int allcount = 0; int counts = 0; void kruskal() { sort(e, e + m, cmp); for (int i = 0; i < m; i++) { int tempx = find(e[i].from); int tempy = find(e[i].to); if (tempx == tempy)continue; father[tempx] = tempy; allcount += e[i].dis; counts++; if (counts == k)break; } } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 0; i < m; i++) scanf("%d%d%d", &e[i].from, &e[i].to, &e[i].dis); for (int i = 0; i <= m; i++)father[i] = i; kruskal(); printf("%d", allcount); }