UVa 10397 - Connect the Campus

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

題目網址
中文網址

給你建築物的座標和已經存在的網路線,計算要把所有建築物連起來最小需要多少成本?(越短越好)
成本不包含一開始存在的網路線!

Solution

用勾股定理算出每兩個建築物的邊,然後把一開始已經存在的網路線建好(對兩個建築物做 union),接著再用剩餘的邊做 Kruskal’s Algorithm 即可解。

Code

UVa 10397UVa 10397 - Connect the Campus
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

//C++11
#include<cstdio>
#include<cmath>
#include<algorithm>
#define B 751

struct Coord
{
int x, y;
inline double getLength(Coord &a);
};
struct Edge
{
//兩建築物和之間的距離
int a, b;
double w;
};

int p[B];
Edge edge[300000];
inline void init(int n);
inline int find(int a);
inline void Union(int a, int b);
double kruskal(int N, int E);//(須連幾條邊,總共有幾個邊)
int main()
{
int N, M, i;
Coord building[B];

while (scanf("%d", &N) != EOF)
{
for (i = 1; i <= N; i++)
scanf("%d%d", &building[i].x, &building[i].y);

//init disjoint-set
init(N);

int a, b, connect = 0;
scanf("%d", &M);
for (i = 0; i < M; i++)
{
scanf("%d%d", &a, &b);
if (find(a) != find(b))
{
Union(a, b);
connect++;//已經連接好的線
}
}

int E = 0;
for (i = 1; i <= N; i++)
for (int j = i + 1; j <= N; j++)
{
if (find(i) != find(j))//判斷是否會因原本接好的成為環
{
edge[E].a = i;
edge[E].b = j;
edge[E++].w = building[i].getLength(building[j]);
}
}

printf("%.2lf\n", kruskal(N - connect - 1, E));
}

return 0;
}
void init(int n)
{
for (int i = 0; i <= n; i++)
p[i] = i;
}
int find(int a)
{
return a == p[a] ? a : (p[a] = find(p[a]));
}
void Union(int a, int b)
{
p[find(a)] = find(b);
}
double Coord::getLength(Coord& a)
{
//勾股定理
double xx = (double)(x - a.x)*(x - a.x);
double yy = (double)(y - a.y)*(y - a.y);

return sqrt(xx + yy);
}
double kruskal(int n, int E)
{
std::sort(edge, edge + E, [](const Edge& a, const Edge& b)->bool{return a.w < b.w; });

double cost = 0;
for (int i = 0, e = 0; i < E&&e < n; i++, e++)
{
while (find(edge[i].a) == find(edge[i].b))
i++;

Union(edge[i].a, edge[i].b);

cost += edge[i].w;
}

return cost;
}