http://poj.org/problem?id=1251
此題一看就知是最小生成樹,由於數據量很小,輸入的數據形式也沒有那一種比較方便,所以prim和kruskal都可以
下面給出kruskal代碼
#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
#include<iostream>
#define MAXEN 200
#define MAXVN 60
using namespace std;
typedef struct{
int u, v, value;
}Edge;
Edge eg[MAXEN];
int p[MAXVN], rank[MAXVN];
vector<Edge> usedEdge;
void MAKE_SET(int x){
p[x] = x;
rank[x] = 0;
}
int FIND_SET(int x){
if(x != p[x])
p[x] = FIND_SET(p[x]);
return p[x];
}
void LINK(int x, int y){
if(rank[x] > rank[y]) p[y] = x;
else{
p[x] = y;
if(rank[x] == rank[y]) rank[y] += 1;
}
}
void UNION_SET(int x, int y){
LINK(FIND_SET(x), FIND_SET(y));
}
int cmp(const void *a, const void *b){
return (*(Edge *)a).value - (*(Edge *)b).value;
}
bool cp(Edge a,Edge b){
return a.value < b.value;
}
int kruskal(int en, int vn){
usedEdge.clear();//printf("sfdds");
for(int i = 1; i <= vn; i++) MAKE_SET(i);
qsort(eg,en,sizeof(eg[0]), cmp);
for(int i = 0; i < en; i++){
if(FIND_SET(eg[i].u) != FIND_SET(eg[i].v)){
UNION_SET(eg[i].u,eg[i].v);
usedEdge.push_back(eg[i]);
}
}
int sum = 0;
for(int i = 0; i < usedEdge.size(); i++) sum+=usedEdge[i].value;
return sum;
}
int main(){
int vn,n, b;
char a;
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
while(cin>>vn && vn){
//getchar();
int count = 0;
for(int i = 1; i < vn; i++){
cin>>a>>n;
//printf("n: %d\n", n);
//getchar();
for(int j = 0; j < n ; j++){
cin>>a>>b;
getchar();
eg[count].u = i;
eg[count].v = a - 'A' +1;
eg[count++].value = b;
}
}
int sum = kruskal(count, vn);
cout<<sum<<endl;
}
}