1034 Head of a Gang python实现
图:字典里装字典
gang:dfs
k:边重复存储,阈值比较需乘2
n,k=[int(x) for x in input().split(" ")]
dic={}
for _ in range(n):
a,b,w=input().split(" ")
w=int(w)
if a not in dic:
dic[a]={b:w}
elif b not in dic[a]:
dic[a][b]=w
else:
dic[a][b]+=w
if b not in dic:
dic[b]={a:w}
elif a not in dic[b]:
dic[b][a]=w
else:
dic[b][a]+=w
visit=[]
res=[]
def dfs(n):
global visit,dic,gang
for c in dic[n].keys():
if c not in visit:
visit.append(c)
gang.append(c)
dfs(c)
for c in dic:
if c not in visit:
gang=[c]
visit.append(c)
dfs(c)
for x in gang:
dic[x]=sum(dic[x].values())
w=sum(dic[x] for x in gang)
if w>2*k and len(gang)>2:
max=dic[gang[0]]
head=gang[0]
for x in gang:
if dic[x]>max:
max=dic[x]
head=x
res.append(" ".join([head,str(len(gang))]))
print(len(res))
res=sorted(res)
for c in res:
print(c)