python数据结构学习笔记-树(下)-习题-file-transfer

Input Specification:
Each input file contains one test case. For each test case, the first line contains N (2≤N≤10​4​​), 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)
        
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值