题目链接:点击打开链接
给出n - 1组边长, 构成一张图, 要求删除一些边使得边长和最小且任意两点可到达.
最小生成树, 套一个kru模板即可. 并查集初始化, 读入数据后对边长进行排序, 若并查集确定两点不在同一连通分量则将两点连接并存储
所得到的边.
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 100;
struct node
{
/* data */
int u, v, w;
}map[MAXN];
int par[30], n;
int find(int x)
{
if(x == par[x]) return x;
return par[x] = find(par[x]);
}
bool cmp(node a, node b)
{
return a.w < b.w;
}
int main(int argc, char const *argv[])
{
while(cin >> n && n) {
for(int i = 0; i < 30; ++i)
par[i] = i;
int num = 0, ans = 0;
for(int i = 0; i < n - 1; ++i) {
char c;
int k;
cin >> c >> k;
for(int j = 0; j < k; ++j) {
char ch;
int x;
cin >> ch >> x;
map[num].u = c - 'A';
map[num].v = ch - 'A';
map[num++].w = x;
}
}
sort(map, map + num, cmp);
for(int i = 0; i < num; ++i) {
int x = find(map[i].u), y = find(map[i].v);
if(x != y) {
ans += map[i].w;
par[x] = y;
}
}
cout << ans << endl;
}
return 0;
}