1. 程式人生 > >還是暢通工程——最小生成樹(王道)

還是暢通工程——最小生成樹(王道)

不一定 要求 LG sin 最小生成樹 bsp 生成樹 結束 operator

題目描述:
某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),並要求鋪設的公路總長度為最小。請計算最小的公路總長度。
輸入:

測試輸入包含若幹測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨後的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。為簡單起見,村莊從1到N編號。
當N為0時,輸入結束,該用例不被處理。

輸出:

對每個測試用例,在1行裏輸出最小的公路總長度。

樣例輸入:
3
1 2 1
1 3 2
2 3 4
4
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0
樣例輸出:
3
5

#include <iostream>
#include<algorithm>
#include<cstdio>
#define N 100
using namespace std;
int Tree[N];
int findRoot(int x){//x值的根節點
    if(Tree[x]==-1)
        return x;
    else{
        int temp=findRoot(Tree[x]);
        Tree[x]
=temp; return temp; } } struct edge{ int a,b; int cost;//邊的權值 bool operator < (const edge &A) const{//重載小於號使其可以按照邊的權值從小到大排列 return cost<A.cost; } }; struct edge edges[200]; int main() { int n; scanf("%d",&n); for(int i=0;i<n*(n-1)/2;i++) scanf(
"%d %d %d",&edges[i].a,&edges[i].b,&edges[i].cost); sort(edges,edges+n*(n-1)/2);//按邊排序 for(int i=0;i<N;i++) Tree[i]=-1; int ans=0; for(int i=0;i<n*(n-1)/2;i++){ int a=findRoot(edges[i].a);//查a的根節點 int b=findRoot(edges[i].b);//查b的根節點 if(a!=b){//ab兩點不是一棵樹上的 Tree[a]=b;//合並兩個集合 ans+=edges[i].cost;//累加該邊權值 } } printf("%d\n",ans); return 0; }

還是暢通工程——最小生成樹(王道)