最小生成树 || HDU 1301 Jungle Roads

时间:2023-03-09 04:26:50
最小生成树 || HDU 1301 Jungle Roads

裸的最小生成树

输入很蓝瘦

**并查集

int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }

找到x在并查集里的根结点,如果两个端点在同一个集合内,find之后两个值就相等了

每次找到权值最小的端点不在同一集合的边 把两个集合合并

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
int fa[];
struct node
{
int s, e, d;
}l[];
bool cmp(node x, node y)
{
if(x.d != y.d) return x.d < y.d;
}
int find(int x)
{
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main()
{
while()
{
int n, i, j, x, val, sum = , cnt = ;//cnt是边数
char c;
scanf("%d", &n);
if(n == ) break;
for(i = ; i < n - ; i++)
{
scanf(" %c", &c);
int s = c - 'A' + ;
scanf("%d", &x);
for(j = ; j < x; j++)
{
scanf(" %c %d", &c, &val);
int e = c - 'A' + ;
l[cnt++] = (node){s, e, val};
}
}
sort(l, l + cnt, cmp);
for(int i = ; i <= n; i++)
fa[i] = i;
for(int i = ; i < cnt; i++)
{
int fs = find(l[i].s), fe = find(l[i].e);
if(fs == fe) continue;
sum += l[i].d;
fa[fs] = fe;
}
printf("%d\n", sum);
}
return ;
}