-
Notifications
You must be signed in to change notification settings - Fork 74
/
merging_tables.py
54 lines (40 loc) · 1.4 KB
/
merging_tables.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
# python3
import sys
n, m = map(int, sys.stdin.readline().split())
lines = list(map(int, sys.stdin.readline().split()))
rank = [1] * n
parent = list(range(0, n))
ans = [max(lines)]
act = {}
def getParent(table):
if table != parent[table]:
parent[table] = getParent(parent[table])
return parent[table]
def merge(destination, source):
realDestination, realSource = getParent(destination), getParent(source)
lineRoot = 0
if realDestination == realSource:
return False
if rank[realDestination] > rank[realSource]:
parent[realSource] = realDestination
lines[realDestination] += lines[realSource]
lineRoot = lines[realDestination]
lines[realSource] = 0
elif rank[realDestination] == rank[realSource]:
parent[realSource] = realDestination
lines[realDestination] += lines[realSource]
lineRoot = lines[realDestination]
lines[realSource] = 0
rank[realDestination] += 1
else:
parent[realDestination] = realSource
lines[realSource] += lines[realDestination]
lineRoot = lines[realSource]
lines[realDestination] = 0
if lineRoot > ans[0]:
ans[0] = lineRoot
return True
for i in range(m):
destination, source = map(int, sys.stdin.readline().split())
merge(destination - 1, source - 1)
print(ans[0])