hdu1879——繼續暢通工程——————【kruskal模板】

以前寫過這道題不止一遍,但是再碰到這個題目的時候還是迷茫,長時間不練習這方面的題目就不會了,看來真的需要堅持碼代碼,不寫會生疏的!
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;//最小生成樹,拓撲排序,最短路徑,二分圖,網絡流。
const int N=110;
int father[N*N];
struct node {

    int st_p;   //左端
    int en_p;   //右端
    int cost;   //邊長

}edge[N*N];
void init(){

    for(int i=0;i<N;i++){

        father[i]=i;

    }
}
int find(int x){

    if(father[x]==x){

        return x;
    }
    else{

        return father[x]=find(father[x]);
    }
}
void Union(int x,int y){

    x=find(x),y=find(y);
    if(x!=y){

        if(x<y){
            father[y]=x;
        }
        else
            father[x]=y;
    }
}
bool cmp(node a,node b){

    return a.cost<b.cost;
}
int kruskal(int k){

    int x,y,ans=0;
    sort(edge,edge+k,cmp);
    for(int i=0;i<k;i++){

        x=edge[i].st_p;
        y=edge[i].en_p;
        x=find(x),y=find(y);
        if(x!=y){

            if(x>y){

                father[x]=y;
            }
            else{

                father[y]=x;
            }
            ans+=edge[i].cost;
        }
    }
    return ans;
}
int main(){

    int n,m,a,c,b,d;
    while(scanf("%d",&n)!=EOF&&n){
        init();
        m=n*(n-1)/2;
        int k=0;
        for(int i=0;i<m;i++){

            scanf("%d%d%d%d",&a,&b,&c,&d);
            if(d==1){
                Union(a,b);
                continue;
            }
            edge[k].st_p=a;
            edge[k].en_p=b;
            edge[k++].cost=c;   
        }
        int ans=kruskal(k);
        printf("%d\n",ans);
    }
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章