POJ - 1251 Jungle Roads (最小生成树&并查集
作者:互联网
#include<iostream> #include<algorithm> using namespace std; int ans=0,tot=0; const int N = 1e5; int f[200]; struct ac{ int v,u,w; }edge[N]; bool cmp(ac a,ac b){ return a.w<b.w; } inline int find(int x){ if(x!=f[x])f[x]=find(f[x]);return f[x]; } inline int join(int x,int y,int w){ int fx=find(x),fy=find(y); if(fx!=fy){ f[fx]=fy;ans+=w;tot++; } } int main() { int n;string a,b;int m,w,cnt=0; while(cin>>n&&n){ //cin.ignore(); ans=tot=cnt=0; for(int i = 1;i <=n;++i)f[i]=i; for(int i = 1;i <n;++i){ cin>>a;cin>>m; while(m--){ cin>>b;cin>>w; edge[cnt].u=a[0]-'A'+1,edge[cnt].v=b[0]-'A'+1,edge[cnt].w=w; cnt++; } } sort(edge,edge+cnt,cmp); for(int i = 0;i < cnt;++i){ join(edge[i].u,edge[i].v,edge[i].w); if(tot==n-1)break; } cout<<ans<<endl; } return 0; }AC代码
https://vjudge.net/problem/POJ-1251
读题读的有点难受,其余很简单
标签:cnt,int,查集,cin,tot,edge,POJ,Jungle,ac 来源: https://www.cnblogs.com/h404nofound/p/11636501.html