1. 程式人生 > >7-3 公路村村通(最小生成樹K演算法)

7-3 公路村村通(最小生成樹K演算法)

7-3 公路村村通(30 分)
現有村落間道路的統計資料表中,列出了有可能建設成標準公路的若干條道路的成本,求使每個村落都有公路連通所需要的最低成本。

輸入格式:
輸入資料包括城鎮數目正整數N(≤1000)和候選道路數目M(≤3N);隨後的M行對應M條道路,每行給出3個正整數,分別是該條道路直接連通的兩個城鎮的編號以及該道路改建的預算成本。為簡單起見,城鎮從1到N編號。

輸出格式:
輸出村村通需要的最低成本。如果輸入資料不足以保證暢通,則輸出−1,表示需要建設更多公路。

輸入樣例:
6 15
1 2 5
1 3 3
1 4 7
1 5 4
1 6 2
2 3 4
2 4 6
2 5 2
2 6 6
3 4 6
3 5 1
3 6 1
4 5 10
4 6 8
5 6 3
輸出樣例:
12

#include<bits/stdc++.h>
using namespace std;
int f[10000];
struct edge{
    int u,v;//頂點u,v;
    long long cost;
}edgeOne;
edge es[10000];
bool cmp(edge e1,edge e2){
    return e1.cost<e2.cost;
}

int V,E;//村莊數和道路數
int fun(int a){
    if(f[a]==a){
        return f[a];
    }
    f[a]=fun(f[a]);
    return
f[a]; } void group(int x,int y){ int tx=fun(x); int ty=fun(y); if(ty!=tx){ f[ty]=tx; } return; } void init(){ for(int i=1;i<=V ;i++){ f[i]=i; } } bool same(int x,int y){ return fun(x)==fun(y); } long long kruskal(){ long long res=0; sort(es+1
,es+E+1,cmp); for(int i=1;i<=E;i++){ if(!same(es[i].u,es[i].v)){ group(es[i].u,es[i].v); res+=es[i].cost; } } return res; } int main(){ long long res=0; //while(scanf("%d%d",&V,&E)==2){ scanf("%d%d",&V,&E); //if(V==0){ // break;} init(); for(int i=1;i<=E;i++){ scanf("%d%d%lld",&es[i].u,&es[i].v,&es[i].cost); } res=kruskal(); for(int j=1;j<=V;j++){ if(!same(j,1)){ res=-1; } } if(res==-1){ printf("-1"); }else{ printf("%lld",res); } return 0; }