還是暢通工程 某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),并要求鋪設的公路總長度為最小。請計算最小的公路總長度。 Input 測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨后的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。為簡單起見,村莊從1到N編號。 當N為0時,輸入結束,該用例不被處理。 Output 對每個測試用例,在1行里輸出最小的公路總長度。 Sample Input 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 Sample Output 3 5
簡單模板題
#include<iostream>#include<cstdio>#include<string.h>#include<algorithm>using namespace std;const int maxn=105;int fa[maxn];void init(){ for(int i=0;i< maxn;i++) fa[i]=i;}int Find(int x){ if(fa[x]== x) return fa[x]; else return fa[x]=Find(fa[x]);}void Union(int x,int y){ int fx=Find(x),fy=Find(y); if( fx!= fy) fa[fx] =fy;}typedef struct{ int st,ed,cost;}Edge;Edge edge[10005];int cmp(Edge a,Edge b){ return a.cost < b.cost;}int main(){ ios_base::sync_with_stdio(false); int n; while(cin>>n,n){ int t1,t2,t3; int m=n*(n-1)/2; for(int i=0;i<m;i++){ cin>>t1>>t2>>t3; edge[i].st= t1; edge[i].ed= t2; edge[i].cost =t3; } init(); sort(edge,edge+m,cmp); int rst=n; int tot_cost =0; for(int i=0; i<m && rst >1 ;i++){ if(Find(edge[i].st) != Find(edge[i].ed)){ Union(edge[i].st,edge[i].ed); rst--; tot_cost +=edge[i].cost; } } cout<<tot_cost<<endl; }}新聞熱點
疑難解答