简单的最小生成树,初学者可以拿来练练手
#include<iostream> #include<string> #include<cstring> #include<cstdio> #include<algorithm> #include<vector> #include<cmath> using namespace std; const int N = 30; int root[N]; struct Edge { int from,to,cost; Edge() { } Edge(const int& from , const int& to,const int& cost):from(from),to(to),cost(cost) {}; Edge(const Edge& res) { (*this).from = res.from; (*this).to= res.to; (*this).cost = res.cost; } bool operator < ( const Edge& res) const { return (*this).cost < res.cost; } }; void InitSet(int n) { for(int i = 1 ; i <= n ; i++) { root[i] = i; } } int FindSet(int x) { if(x != root[x]) { root[x] = FindSet(root[x]); } return root[x]; } void UnionSet(int a,int b) { int x = FindSet(a); int y = FindSet(b); if(x != y) { root[x] = y; } } vector<Edge>v; void InitGraph(int n) { v.clear(); string from,to; int num,cost; for(int i = 0 ; i < n ; i++) { cin>>from>>num; for(int j = 0 ; j < num ; j++) { cin>>to>>cost; v.push_back(Edge(from[0] - 'A' + 1,to[0] - 'A' + 1,cost)); } } } int MST(int n) { int ans = 0; InitSet(n); sort(v.begin(),v.end()); for(vector<Edge>::iterator it = v.begin() ; it != v.end() ; it++) { int a = (*it).from; int b = (*it).to; int cost = (*it).cost; if( FindSet(a) != FindSet(b) ) { UnionSet(a,b); ans += cost; } } return ans; } int main() { #ifdef LOCAL freopen("in.txt","r",stdin); #endif // LOCAL int n; while(scanf("%d",&n) && n) { InitGraph(n-1); int ans = MST(n); cout<<ans<<endl; } return 0; }