-
Notifications
You must be signed in to change notification settings - Fork 0
/
GraphConnectivity.py
61 lines (49 loc) · 997 Bytes
/
GraphConnectivity.py
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
# https://vjudge.net/problem/UVA-459
def char2int(char):
return ord(char) - ord("A")
def find(parent, x):
if parent[x] != x:
parent[x] = find(parent, parent[x])
return parent[x]
def union(parent, ranks, u, v):
pu = find(parent, u)
pv = find(parent, v)
if pu == pv: return
if ranks[pu] > ranks[pv]:
parent[pv] = pu
elif ranks[pu] < ranks[pv]:
parent[pu] = pv
else:
parent[pu] = pv
ranks[pv] += 1
T = int(input())
input()
for case in range(T):
n = char2int(input().strip()) + 1
parent = list(range(n))
ranks = [0] * n
while True:
try:
line = input().strip()
except EOFError: break
if line == '': break
else:
u, v = char2int(line[0]), char2int(line[1])
union(parent, ranks, u, v)
res = set(find(parent, i) for i in range(n))
print(len(res))
if case < T - 1:
print()
"""
2
E
AB
CE
DB
EC
E
AB
CE
DB
EC
"""