zcmu-4926: 還是暢通工程(終於邁出並查集這一步了)
阿新 • • 發佈:2018-11-24
4926: 還是暢通工程
Time Limit: 1 Sec Memory Limit: 32 MB
Submit: 40 Solved: 27
[Submit][Status][Web Board]Description
某省調查鄉村交通狀況,得到的統計表中列出了任意兩村莊間的距離。省政府“暢通工程”的目標是使全省任何兩個村莊間都可以實現公路交通(但不一定有直接的公路相連,只要能間接通過公路可達即可),並要求鋪設的公路總長度為最小。請計算最小的公路總長度。
Input
測試輸入包含若干測試用例。每個測試用例的第1行給出村莊數目N ( < 100 );隨後的N(N-1)/2行對應村莊間的距離,每行給出一對正整數,分別是兩個村莊的編號,以及此兩村莊間的距離。為簡單起見,村莊從1到N編號。
當N為0時,輸入結束,該用例不被處理。Output
對每個測試用例,在1行裡輸出最小的公路總長度。
Sample Input
8 1 2 42 1 3 68 1 4 35 1 5 1 1 6 70 1 7 25 1 8 79 2 3 59 2 4 63 2 5 65 2 6 6 2 7 46 2 8 82 3 4 28 3 5 62 3 6 92 3 7 96 3 8 43 4 5 28 4 6 37 4 7 92 4 8 5 5 6 3 5 7 54 5 8 93 6 7 83 6 8 22 7 8 17 0
Sample Output
82
程式碼參考部落格連結
正在學習並查集中..
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <iostream> #define go(i,a,b) for(int i=a;i<=b;i++) #define mem(a) memset(a,0,sizeof(a)) using namespace std; const int maxn = 1e4 + 5; typedef struct{ int to,next,len; }node; node a[maxn]; int fa[maxn]; int n; bool cmp(node a,node b) { return a.len < b.len; } int find(int x) { if(x == fa[x]) return x; else return find(fa[x]); } int main() { while(scanf("%d",&n) && n) { go(i,1,n) fa[i] = i; int minn = 0; go(i,1,n*(n-1)/2) cin>>a[i].to>>a[i].next>>a[i].len; sort(a+1,a+n*(n-1)/2+1,cmp); go(i,1,n*(n-1)/2) { if(find(a[i].to) != find(a[i].next)) { minn += a[i].len; fa[find(a[i].to)] = a[i].next; } } cout<<minn<<endl; } return 0; }