首页 > 代码库 > HDU 1879 继续畅通工程

HDU 1879 继续畅通工程

最小生成树

 

 1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <algorithm> 5 #include <cmath> 6 using namespace std; 7  8 const int maxn=105; 9 10 int x[maxn],y[maxn];11 int v[maxn*maxn],u[maxn*maxn],w[maxn*maxn];12 int fa[maxn];13 int r[maxn*maxn];14 15 bool cmp (int x,int y){16     return w[x]<w[y];17 }18 19 int find (int x){20     if (fa[x]==x)21         return x;22     return fa[x]=find (fa[x]);23 }24 25 int main (){26     int t;27     //scanf ("%d",&t);28     int n;29     while (~scanf ("%d",&n)&&n){30         int m=n*(n-1)/2;31         for (int i=0;i<m;i++){32             int a,b;33             scanf ("%d%d%d%d",&v[i],&u[i],&a,&b);34             if (b)35                 w[i]=0;36             else w[i]=a;37         }38         for (int i=1;i<=n;i++)39             fa[i]=i;40         for (int i=0;i<m;i++)41             r[i]=i;42         int temp=0;43         sort (r,r+m,cmp);44         long long ans=0;45         for (int i=0;i<m;i++){46             int fv=find(v[r[i]]);47             int fu=find(u[r[i]]);48             if (fv!=fu){49                 ans+=w[r[i]];50                 temp++;51                 fa[fv]=fu;52             }//cout<<w[r[i]]<<" ";53         }54         //if (temp==n-1)55             printf ("%I64d\n",ans);56     }57     return 0;58 }

 

HDU 1879 继续畅通工程