题意:
第一行给一个N,代表这里有N- 1 个村庄,接下来有 N- 1 行,每行开头输入一个大写字母 C 代表第 i 个村庄的编号,随后有一个数字 m 代表 C 这个村庄和 m 个村庄相连,随后再给出 m 组数据,每组输入由一个大写字母 F 和 数字 w 组成,代表 C 和 F 之间的距离为 W;当N== 0时程序结束。
思路:
因为题目中给出的字母为 A - Z 那么我这里用数字 1 - 26代替村庄的编号,然后求最小生成树。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
using namespace std;
const int MAXN = 29;
int pre[MAXN];
int n,m;
struct Node //储存数据
{
int u, v, w;
}cy[103];
void debug()
{
for(int i =1; i<m; i++)
cout << cy[i].u << " "<< cy[i].v <<" "<< cy[i].w <<endl;
}
int Find(int x) //并查集
{
return x == pre[x] ? x :(pre[x] = Find(pre[x]));
}
int mycmp(Node a,Node b)
{
return a.w < b.w;
}
void mst()
{
for(int i = 0 ; i < MAXN; i++)
pre[i] = i;
}
int kru()
{
int ans = 0;
int cnt = 0;
sort(cy + 1, cy + m , mycmp);
//cout << endl;
//debug();
for(int i = 1; i < m; i++) //从最小的那条边开始寻找
{
int fv = Find(cy[i].v);
int fu = Find(cy[i].u);
if(fv != fu) //如果不在一个集合就把当前这条比较小的加进去
{
pre[fv] = fu;
ans += cy[i].w;
cnt ++;
}
if(cnt == n -1) //构成了最小生成树
{
break;
}
}
return ans;
//cout <<"ans " << ans <<endl;
}
int main()
{
//freopen("in.cpp","r",stdin);
while(cin >> n && n)
{
mst();
m = 1;
for(int j = 1; j < n; j++)
{
char s[29][3] = {0};
cin >> s[0];
int k;
cin >> k;
for(int i = 1; i <= k; i++)
{
int wh;
cin >> s[i] >> wh;
cy[m].u = s[0][0] - 'A' + 1;
cy[m].v = s[i][0] - 'A' + 1;
cy[m].w = wh;
m++;
}
}
cout << kru() << endl;
}
return 0;
}