23集合小白专场TSSN实现

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
'''
5 #5个元素
c 3 2 no
i 3 2
c 3 2 yes
i 4 5
i 2 4
c 3 5 yes
i 1 3
c 1 5 yes
s # 输出the network is connected

主框架
main()
while :
读入指令集
处理指令
return

'''
def main(L):
S = L.pop(0)[0] * [-1] #S 是集合。
for o in L:
print(o,o[0])
if o[0] == 'i':
Input_connection(o[1],o[2],S)
if o[0] == 'c':
Check_connection(o[1],o[2],S)
if o[0] == 's':
Check_network(S)
# return S

def find(x,s):
while s[x] >= 0:
x = s[x]
return x
def union(x,y,s=[]): # 有潜在问题,下一课解决。
s[y] = x

def Input_connection(node1,node2,S):
root1 = find(node1-1,S) # node1 - 1 是为了做映射 。
root2 = find(node2-1,S)
if root1 != root2: # 如果是两个集合,就连接两个点。
union(root1,root2,S)
def Check_connection(node1,node2,S):
root1 = find(node1-1,S)
root2 = find(node2-1,S)
if root1 == root2:
print('yes')
else:
print('no')
def Check_network(S): # 集合数量。
num = 0
for i in range(len(S)):
if S[i] < 0:
num += 1
if num == 1:
print('the network is connected')
else:
print('there are %d components.'%num)

if __name__ == '__main__':
L = [[5] ,
['c', 3, 2] ,
['i', 3, 2],
['c', 3, 2] ,
['i', 4, 5],
['i', 2, 4],
['c', 3, 5],
['i', 1, 3],
['c', 1, 5],
['s'] ]

main(L)