码迷,mamicode.com
首页 > 其他好文 > 详细

[HDOJ1301]

时间:2015-10-26 22:02:38      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1301

 

最小生成树 (Kruskal)

 1 #pragma warning(disable:4996)
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <iomanip>
 5 #include <cstring>
 6 #include <climits>
 7 #include <complex>
 8 #include <fstream>
 9 #include <cassert>
10 #include <cstdio>
11 #include <bitset>
12 #include <vector>
13 #include <deque>
14 #include <queue>
15 #include <stack>
16 #include <ctime>
17 #include <set>
18 #include <map>
19 #include <cmath>
20 
21 using namespace std;
22 
23 typedef struct Node {
24     int a;
25     int b;
26     int v;
27     friend bool operator < (Node a, Node b) {
28         return a.v > b.v;
29     }
30 }Node;
31 
32 const int maxn = 20010;
33 int pre[maxn];
34 int n, ans;
35 Node p;
36 priority_queue<Node> pq;
37 
38 int find(int x) {
39     return x == pre[x] ? x : pre[x] = find(pre[x]);
40 }
41 
42 bool unite(int x, int y) {
43     x = find(x);
44     y = find(y);
45     if (x != y) {
46         pre[y] = x;
47         return true;
48     }
49     return false;
50 }
51 inline void init() {
52     for (int i = 0; i < maxn; i++) {
53         pre[i] = i;
54     }
55     while (!pq.empty())    pq.pop();
56 }
57 
58 int main() {
59     // freopen("in", "r", stdin);
60     while (~scanf("%d", &n) && n) {
61         init();
62         char a[2], b[2];
63         int cnt = 0;
64         int m, v;
65         ans = 0;
66         n--;
67         for (int i = 0; i < n; i++) {
68             scanf("%s %d", &a, &m);
69             for (int i = 0; i < m; i++) {
70                 scanf("%s %d", &b, &v);
71                 p.a = a[0] - A;
72                 p.b = b[0] - A;
73                 p.v = v;
74                 pq.push(p);
75             }
76         }
77         while (n) {
78             p = pq.top();
79             pq.pop();
80             if (unite(p.a, p.b)) {
81                 n--;
82                 ans += p.v;
83             }
84         }
85         printf("%d\n", ans);
86     }
87 }

 

[HDOJ1301]

标签:

原文地址:http://www.cnblogs.com/vincentX/p/4912350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!