KY138 Head of a Gang

KY138 Head of a Gang

def getRoot(RootDict, child):
    if child == RootDict[child]:
        return child
    else:
        root = getRoot(RootDict, RootDict[child])
        RootDict[child] = root
        return root

def main():
    N_call, K_thresh = map(eval, input().strip().split())
    VertexSet, EdgeWeightDict = set(), dict()
    VertexWeightDict, HeightDict, RootDict = dict(), dict(), dict()
    for i in range(N_call):
        name1, name2, weight = input().strip().split()
        RootDict[name1], RootDict[name2] = RootDict.get(name1, name1), RootDict.get(name2, name2)
        weight = eval(weight)
        VertexSet.update({name1,name2})
        HeightDict[name1], HeightDict[name2] = HeightDict.get(name1, 1), HeightDict.get(name2, 1)
        if name1 == name2:
            continue
        EdgeWeightDict[(name1, name2)] = EdgeWeightDict.get((name1, name2), 0) + weight
        EdgeWeightDict[(name2, name1)] = EdgeWeightDict.get((name2, name1), 0) + weight
        VertexWeightDict[name1] = VertexWeightDict.get(name1, 0) + weight
        VertexWeightDict[name2] = VertexWeightDict.get(name2, 0) + weight
        root1, root2 = getRoot(RootDict, name1), getRoot(RootDict, name2)
        height1, height2 = HeightDict.get(root1, 1), HeightDict.get(root2, 1)
        if height1 == height2:
            RootDict[root2] = root1
            HeightDict[root1] += 1
        elif height1 > height2:
            RootDict[root2] = root1
        else:
            RootDict[root1] = root2
    for v in VertexSet:
        RootDict[v] = getRoot(RootDict, v)
    rootNames = set([r for r in RootDict.values()])
    gangsList = list()
    for root in rootNames:
        gang = list()
        for c, r in RootDict.items():
            if r == root:
                gang.append(c)
        gangsList.append(gang)
    result = list()
    for gang in gangsList:
        if len(gang) < 3:
            continue
        totalTime = sum([VertexWeightDict[g] for g in gang])
        if totalTime <= 2 * K_thresh:
            continue
        gangInfo = [(g, VertexWeightDict[g]) for g in gang]
        gangInfo.sort(key=lambda x:x[1])
        result.append((gangInfo[-1][0],len(gang)))
    result.sort(key=lambda x:x[0])
    print(len(result))
    for item in result:
        print(*item)

if __name__ == '__main__':
    try:
        while True:
            main()
    except:
        pass
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值