http://ac.jobdu.com/problem.php?pid=1154
最小生成树:堆+并查集
#include <stdio.h>
#include <queue>
typedef struct edge{
int l,r,w;
bool friend operator < (struct edge a, struct edge b){
return a.w > b.w;
}
} Edge;
static int father[27];
int find(int u){
return u == father[u] ? u : father[u] = find(father[u]);
}
int main(){
//freopen("in/1154.in","r",stdin);
int n,k,cost;
char nodef[2],nodet[2];
Edge e;
std::priority_queue<Edge> pq;
while(scanf("%d",&n) && n ){
for (int i = 0; i < 27; ++i) {
father[i] = i;
}
while(!pq.empty()) pq.pop();
for (int i = 1; i < n; ++i) {
scanf("%s %d",nodef,&k);
for (int j = 0; j < k; ++j) {
scanf("%s %d",nodet,&cost);
e.l = nodef[0] - 'A';
e.r = nodet[0] - 'A';
e.w = cost;
pq.push(e);
e.l = nodet[0] - 'A';
e.r = nodef[0] - 'A';
pq.push(e);
}
}
int nRoad = 0,total_cost = 0;
while(!pq.empty() && nRoad < n-1){
e = pq.top();
pq.pop();
//printf("%c %c %d\n",e.l+'A',e.r+'A',e.w);
if(find(e.l) != find(e.r)){
father[find(e.r)] = find(e.l);
total_cost += e.w;
nRoad++;
}
}
if(nRoad == n-1) printf("%d\n",total_cost);
else printf("-1\n");
}
}