首页 > 代码库 > HDU 4463: Outlets

HDU 4463: Outlets

http://acm.hdu.edu.cn/showproblem.php?pid=4463

 

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cmath>
 4 #include <iomanip>
 5 //n:= # of vertices
 6 using namespace std;
 7 const int MAXN = 55;
 8 typedef pair<int, int> PII;
 9 PII coord[MAXN];
10 int parent[MAXN];
11 int n, tot, p, q;
12 
13 int Find(int x)//finds the subset of the x-th element and
14 {
15     //updates its predecessors for furture efficiency
16     return (parent[x] == x) ? x : parent[x] = Find(parent[x]);
17 }
18 void Union(int x, int y)//units two subsets in to a single subset,
19 {
20     //called when they should share the same parent
21     parent[Find(x)] = Find(y);
22 }
23 struct Edge
24 {
25     int from, to;
26     double length;
27     Edge() {};
28     Edge(int f, int t, double l) :from(f), to(t), length(l)
29     {
30 
31     };
32     friend bool operator<(const Edge &e, const Edge &f)
33     {
34         return e.length<f.length;
35     };
36     friend bool operator==(const Edge &e, const Edge &f)
37     {
38         return e.from == f.from&&e.to == f.to;
39     };
40 } edge[MAXN*MAXN / 2], NA;
41 
42 
43 double Kruskal()
44 {
45 
46     /**initialization*/
47     for (int i = 1; i <= n; i++) //the index of an element represents the subset it belongs to,
48         parent[i] = i;              //so initially itself
49     sort(edge + 1, edge + tot + 1);
50     double res = NA.length;
51     parent[Find(NA.from)] = Find(NA.to);//add the road connecting Nike and Apple first
52     for (int i = 1; i <= tot; i++)
53     {
54         if (edge[i] == NA)continue;
55         int u = Find(edge[i].from), v = Find(edge[i].to);
56         if (u != v)
57         {
58             parent[u] = v;
59             res += edge[i].length;
60         }
61     }
62     return res;
63 }
64 int main()
65 {
66     while (cin >> n&&n)
67     {
68         cin >> p >> q;
69         tot = 0;
70         for (int i = 1; i <= n; i++)
71             scanf("%d%d", &coord[i].first, &coord[i].second);
72         /**add edges*/
73         for (int i = 1; i <= n; i++)
74             for (int j = 1; j < i; j++)
75             {
76                 edge[++tot] = Edge(i, j, hypot(coord[i].first - coord[j].first, coord[i].second - coord[j].second));
77                 if ((i == p&&j == q) || (i == q&&j == p))NA = edge[tot];
78             }
79         /**Kruskal*/
80         cout << fixed << setprecision(2) << Kruskal() << \n;
81 
82     }
83     return 0;
84 }

 

HDU 4463: Outlets