UVa 1013 - Island Hopping

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

島嶼居民要建造網路連到本島,假設現在島嶼跟島嶼之間都沒有架設網路線,現在開始建造網路,使得每一個島嶼都可以與本島或者是間接相連。

請問平均等待時間需要多少。

所有的路線,在同一時刻開始建造,以每一天一公里的速度建造所有的邊,而每一條邊都以歐幾里得距離為路線長度。

Sample Input

1
2
3
4
5
6
7
8
9
7
11 12 2500
14 17 1500
9 9 750
7 15 600
19 16 500
8 18 400
15 21 250
0

Sample Output

1
Island Group: 1 Average 3.20

Solution

一開始沒有注意到同時建造,發現這條規則後,將所有邊的長度由小到大排序,使用并查集去紀錄,找到第一個時刻連到本島的時間。

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
#include <stdio.h>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
const int MAXN = 64;
double X[MAXN], Y[MAXN], M[MAXN];
struct Edge {
int x, y;
double v;
Edge(int a = 0, int b = 0, double c = 0):
x(a), y(b), v(c) {}
bool operator<(const Edge &x) const {
return v < x.v;
}
};
vector<Edge> E;
int parent[MAXN], weight[MAXN];
double weight2[MAXN];
int findp(int x) {
return parent[x] == x ? x : parent[x] = findp(parent[x]);
}
int joint(int x, int y) {
x = findp(x), y = findp(y);
if (x == y)
return 0;
if (weight[x] > weight[y]) {
parent[y] = x, weight[x] += weight[y];
weight2[x] += weight2[y];
} else {
parent[x] = y, weight[y] += weight[x];
weight2[y] += weight2[x];
}
return 1;
}
double solve(int n) {
sort(E.begin(), E.end());
double div = 0, sum = 0;
int u, v;
for (int i = 0; i < n; i++)
parent[i] = i, weight[i] = 1, weight2[i] = M[i], div += M[i];
for (int i = 0; i < E.size(); i++) {
u = E[i].x, v = E[i].y;
if (findp(u) != findp(v)) {
if (findp(u) == findp(0))
sum += weight2[findp(v)] * E[i].v;
if (findp(v) == findp(0))
sum += weight2[findp(u)] * E[i].v;
joint(u, v);
}
}
return sum / div;
}
int main() {
int n, cases = 0;
while (scanf("%d", &n) == 1 && n) {
for (int i = 0; i < n; i++)
scanf("%lf %lf %lf", &X[i], &Y[i], &M[i]);
E.clear();
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
double v = hypot(X[i] - X[j], Y[i] - Y[j]);
E.push_back(Edge(i, j, v));
}
}
double ret = solve(n);
printf("Island Group: %d Average %.2lf\n", ++cases, ret);
puts("");
}
return 0;
}
/*
7
11 12 2500
14 17 1500
9 9 750
7 15 600
19 16 500
8 18 400
15 21 250
0
*/