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
KY138 Head of a Gang
最新推荐文章于 2024-10-03 09:00:56 发布