Input Specification:
Each input file contains one test case. For each test case, the first line contains N (2≤N≤104), the total number of computers in a network. Each computer in the network is then represented by a positive integer between 1 and N. Then in the following lines, the input is given in the format:
I c1 c2
where I stands for inputting a connection between c1 and c2; or
C c1 c2
where C stands for checking if it is possible to transfer files between c1 and c2; or
S
where S stands for stopping this case.
Output Specification:
For each C case, print in one line the word “yes” or “no” if it is possible or impossible to transfer files between c1 and c2, respectively. At the end of each case, print in one line “The network is connected.” if there is a path between any pair of computers; or “There are k components.” where k is the number of connected components in this network.
考察集合的知识
# file transfer
def find_root(x):
pos = x - 1
while ini_list[pos] > 0:
pos = ini_list[pos]
return pos
def check(c1, c2):
if find_root(c1) == find_root(c2): # 根节点相同则为联通
print('yes')
else:
print('no')
def connect(c1, c2):
r1 = find_root(c1)
r2 = find_root(c2)
if ini_list[r1] < ini_list[r2]: # 按秩归并(小树靠在大树上)
ini_list[r1] += ini_list[r2] # 根节点处,数组存储-N,N为现在属于该树的节点个数
ini_list[r2] = r1
else:
ini_list[r2] += ini_list[r1]
ini_list[r1] = r2
def how_many():
cc = 0
for i in range(n):
if ini_list[i] < 0: # 寻找根节点的个数
cc += 1
if cc == 1:
print('The network is connected.')
else:
print('There are {} components.'.format(cc))
n = int(input())
ini_list = [-1] * n # 数组存放下标节点(+1)的父节点的位置,因为数组从0开始,数据从1开始,根节点为负数
while True:
s = input()
if s == 'S':
how_many()
break
order, s1, s2 = s.split(' ')
n1 = int(s1)
n2 = int(s2)
if order == 'C':
check(n1, n2)
else:
connect(n1, n2)