题意:最小生成树裸题,求图的最小生成树权值
思路:kruskal
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int maxn = 10005;
int p, r, u[maxn];
struct node {
int u, v, w;
node(int u = 0, int v = 0, int w = 0) : u(u), v(v), w(w) {}
}edge[maxn];
int ufind(int x)
{
if (u[x] != x)
u[x] = ufind(u[x]);
return u[x];
}
void unite(int x, int y)
{
u[ufind(x)] = ufind(y);
}
bool cmp(node x, node y)
{
return x.w < y.w;
}
int main()
{
while (cin >> p && p) {
cin >> r;
for (int i = 0; i <= p; i++)
u[i] = i;
for (int i = 0; i < r; i++)
cin >> edge[i].u >> edge[i].v >> edge[i].w;
sort(edge, edge+r, cmp);
int k = 0, res = 0;;
for (int i = 0; i < r; i++) {
int x = edge[i].u, y = edge[i].v;
if (ufind(x) != ufind(y)) {
unite(x, y);
k++;
res += edge[i].w;
}
if (k == p-1)
break;
}
cout << res << endl;
}
return 0;
}