Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 30793 Accepted Submission(s): 13822
当N为0时,输入结束,该用例不被处理。
![[HDOJ1233]还是畅通工程第1张](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![[HDOJ1233]还是畅通工程第2张](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 #include <iostream> 2 #include <queue> 3 #include <cstdio> 4 #include <cstring> 5 #define MAXN 100000 6 7 using namespace std; 8 9 int pre[MAXN]; 10 struct Node { 11 int x; 12 int y; 13 int d; 14 friend bool operator < (Node a, Node b) { 15 return a.d > b.d; 16 } 17 }; 18 19 int find(int x) { 20 return x == pre[x] ? x : pre[x] = find(pre[x]); 21 } 22 23 int unite(int x, int y) { 24 x = find(x); 25 y = find(y); 26 if(x != y) { 27 pre[x] = y; 28 return 1; 29 } 30 return 0; 31 } 32 33 int main() { 34 int N, n, ans; 35 while(~scanf("%d", &N) && N != 0) { 36 ans = 0; 37 n = N * (N - 1) / 2; 38 priority_queue<Node> q; 39 Node tmp; 40 for(int i = 1; i <= n; i++) { 41 scanf("%d %d %d", &tmp.x, &tmp.y, &tmp.d); 42 pre[i] = i; 43 q.push(tmp); 44 } 45 N = N - 1; 46 while(N) { 47 tmp = q.top(); 48 q.pop(); 49 if(unite(tmp.x, tmp.y)) { 50 N--; 51 ans += tmp.d; 52 } 53 } 54 printf("%d ", ans); 55 } 56 return 0; 57 }