UVa 12671 - Disjoint water supply

contents

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

Problem

給一張圖,問有多少對 (u, v) 沒有連通路徑。

Sample Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
6 6
1 2
1 3
1 4
2 5
2 6
3 6
8 11
1 2
1 3
1 4
2 5
3 4
6 7
3 6
3 7
4 8
2 6
5 6

Sample Output

1
2
14
26

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
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <assert.h>
#include <map>
#include <algorithm>
using namespace std;
int parent[32767], weight[32767];
int findp(int x) {
return parent[x] == x ? x : parent[x] = findp(parent[x]);
}
int main() {
int n, m, x, y;
while (scanf("%d %d", &n, &m) == 2 && n) {
for (int i = 0; i <= n; i++) {
parent[i] = 0, weight[i] = 0;
}
vector<int> g[1024];
for (int i = 0; i < m; i++) {
scanf("%d %d", &x, &y);
if (x == 1) {
parent[y] = y;
} else
g[y].push_back(x);
}
for (int i = 2; i <= n; i++) {
for (int j = 0; j < g[i].size(); j++) {
int u = g[i][j];
if (parent[i] == 0)
parent[i] = u;
else if(findp(i) != findp(u))
parent[i] = i;
}
}
for (int i = 2; i <= n; i++) {
weight[findp(i)]++;
}
int ret = 0;
for (int i = 2; i <= n; i++) {
if (i == parent[i]) {
ret += weight[i] * (n - 1 - weight[i]);
}
}
printf("%d\n", ret/2 + n - 1);
}
return 0;
}