UVa 10842 - Traffic Flow

Contents

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

Problem

題目網址

因為道路部門超出預算,需要把 不會使任何路口斷掉 的路給關閉,保留的路當中,盡可能有最大的容量,而在這保留的路中,容量最小的路則為我們要求的。

Solution

利用 Kruskal’s Algorithm ,做最大生成樹即可,記得要求的是生成樹中最後一個,也就是樹中最小的。

Code

UVa 10842UVa 10842 - Traffic Flow
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

#include<cstdio>
#include<algorithm>

struct Road
{
int u, v, c;
}road[10001];

int p[101], rank[101];
inline void init(int n);
inline int find(int n);
inline void Union(int a, int b);
int kruskal(int V, int E);
int main()
{
int Case;
scanf("%d", &Case);

for (int c = 1; c <= Case; c++)
{
int n, m;
scanf("%d%d", &n, &m);

for (int i = 0; i < m; i++)
scanf("%d%d%d", &road[i].u, &road[i].v, &road[i].c);

printf("Case #%d: %d\n", c, kruskal(n, m));
}

return 0;
}
inline void init(int n)
{
for (int i = 0; i < n; i++)
{
p[i] = i;
rank[i] = 0;
}
}
inline int find(int n)
{
return p[n] == n ? n : (p[n] = find(p[n]));
}
inline void Union(int a, int b)
{
a = find(a);
b = find(b);
if (rank[a]>rank[b])
p[b] = a;
else if (rank[a] < rank[b])
p[a] = b;
else
{
p[a] = b;
rank[b]++;
}
}
int kruskal(int V, int E)
{
init(V);
std::sort(road, road + E, [](const Road& a, const Road& b)->bool{return a.c > b.c; });

int capacity = 0;
for (int i = 0, e = 0; i < E&&e < V - 1; i++)
{
while (find(road[i].u) == find(road[i].v))
i++;

Union(road[i].u, road[i].v);
e++;

if (e == V - 1)
capacity = road[i].c;//保留的路中,capacity 最小的
}

return capacity;
}