思路:并查集的板子,重点是字符的转换,不能忘了加上1。
#include<cmath> #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> using namespace std; int n; int fa[27]; struct prog{ int x,y,z; }v[80]; bool cmp( prog a , prog b){ return a.z<b.z; } int find(int x){ return x==fa[x]?x:fa[x]=find(fa[x]); } int main(){ while (scanf("%d",&n)&&n){ for(int i=1;i<=27;i++) fa[i]=i; int k=1; for(int i=1;i<=n-1;i++){ char str[3];int m; cin>>str>>m; for(int j=1;j<=m;j++,k++){ char str2[3];int t; cin>>str2>>t ; v[k].x=(str[0]-'A'+1); v[k].y=(str2[0]-'A'+1); v[k].z=t; } } sort(v+1,v+1+k,cmp); int ans=0; for(int i=1;i<=k;i++){ int dx=find(v[i].x); int dy=find(v[i].y); if(dx==dy) continue; ans+=v[i].z; fa[dx]=dy; } cout<<ans<<endl; } return 0; }