HDU 1879 继续畅通工程(最小生成树 Kruskal算法)

    技术2022-06-12  49

    #include<iostream> #include<cstring> #include<algorithm> using namespace std; #define M 101 typedef struct egde{ int e,s,weight; bool build; }egde; egde info[M*M/2]; int c[M],n,num; bool cmp(const egde a,const egde b){ if(a.build!=b.build) return a.build<b.build; return a.weight<b.weight; } int Find(int x){ while(x!=c[x]) x=c[x]; return x; } bool Union(int x,int y){ int a=Find(x),b=Find(y); if(a==b) return false; num++; c[a]=b; return true; } void init(){ int b; num=0; for(int i=1;i<=n*(n-1)/2;i++){ scanf("%d %d %d %d",&info[i].e,&info[i].s,&info[i].weight,&b); info[i].build=b?false:true; i<=n?c[i]=i:1; } sort(info+1,info+n*(n-1)/2+1,cmp); } int MST_Kruskal(){ int mincost=0; for(int i=1;i<=n*(n-1)/2 && num<n-1 ;i++){ if(Union(info[i].s,info[i].e)) mincost+=info[i].weight*info[i].build; } return mincost; } int main(){ while(cin>>n && n){ init(); cout<<MST_Kruskal()<<endl; } return 0; }


    最新回复(0)