P1195 口袋的天空【贪心+kruskal】
题目
https://www.luogu.com.cn/problem/P1195
分析
本题运用了一个贪心的思想,连接一条边就相当于连通块减1,运用kruskal算法的思想:每次连可以连的边中代价最小的 (贪心) 使用 并查集维护
代码
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<algorithm> using namespace std; #define maxn 10010 #define maxm 10010 struct node { int from; int to; int dis; }e[maxm * 2]; int edges[maxn][maxn]; 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+1, e + m+1, cmp); for (int i = 1; i <=m; i++) { int tempx = find(e[i].from); int tempy = find(e[i].to); if (tempx == tempy)continue; counts++; father[tempx] = tempy; allcount += e[i].dis; if (counts== n - k) { printf("%d", allcount); return; } } printf("No Answer\n"); return; } int main() { scanf("%d%d%d", &n, &m, &k); for (int i = 1; i <=m; i++) { scanf("%d%d%d", &e[i].from, &e[i].to, &e[i].dis); } for (int i = 0; i <= n; i++)father[i] = i; kruskal(); }