POJ 1287Networking
题意:多组数据输入的最小生成树果题
#include<algorithm> #include<iostream> #include<queue> #include<map> #include<vector> #include<stack> #include<set> #include<cstring> #include<cstdio> using namespace std; int first[505]; int vis[505]; typedef struct node{ int x; int y; int date; friend bool operator< (node a,node b){ return a.date<b.date; } }node; void csh(int m){ for(int i=1;i<=m;i++){ first[i]=i; } for(int i=1;i<=m;i++){ vis[i]=1; } } int find(int x){ if(first[x]==x) return x; else{ return find(first[x]); } } void hb(int x,int y){ x=find(x); y=find(y); if(x!=y){ if(vis[x]>vis[y]){ first[y]=x; } else{ first[x]=y; if(vis[x]==vis[y]){ vis[y]++; } } } } node a[250010]; int main(){ int m,n; while(cin>>m&&m!=0){ cin>>n; csh(m); int d,b,c; for(int i=1;i<=n;i++){ cin>>d>>b>>c; a[i].x=d;a[i].y=b;a[i].date=c; } sort(a+1,a+n+1); int ans=0; int t=0; for(int i=1;i<=n;i++){ if(find(a[i].x)==find(a[i].y)) continue; else{ t++;ans+=a[i].date; hb(a[i].x,a[i].y); if(t==(n-1)){ break; } } } cout<<ans<<endl; } return 0; }