并查集

来源:互联网 发布:影响原油数据 编辑:程序博客网 时间:2024/05/29 16:43
2015 netease autunm campus recruitment
union_find
#encoding=utf8def find_father(s):    if s in root_num:        return s    if s in father_dict:        return find_father(father_dict[s])    return NoneN = int(raw_input())f = []while N:    N-=1    f.append(raw_input().split(' '))root_num = {}father_dict = {}for i in f:    a = i[0]    b = i[1]    af = find_father(a)    bf = find_father(b)    if not af and not bf:        father_dict[a] = a        father_dict[b] = a        if a != b:            root_num[a] = 2        else:            root_num[a] = 1    elif None in (af,bf):        if af is None:            father = bf            nof = a        else:            father = af            nof = b        father_dict[nof] = father        root_num[father] += 1    elif af != bf:        ra = root_num[af]        rb = root_num[bf]        if ra > rb:            br = af            sr = bf        else:            br = bf            sr = af        root_num[br] += root_num[sr]        father_dict[sr] = br        root_num.pop(sr)data = sorted(root_num.values(),reverse=True)for i in data:print i
0 0