题解 | 探索宇宙中的星系联盟
探索宇宙中的星系联盟
https://www.nowcoder.com/practice/888ca0b08bdb4eb099b93432a131ca67
const rl = require("readline").createInterface({ input: process.stdin });
var iter = rl[Symbol.asyncIterator]();
const readline = async () => (await iter.next()).value;
void async function () {
let n=0,m=0
const names=[]
const ways= []
let map=new Map()
while(line = await readline()){
if(!n && !m) n=Number(line)
else if(n && !m && map.size<n){
let tokens=line.split(" ")
names.push(tokens[0])
map.set(tokens[0],Number(tokens[1]))
}
else if(map.size==n && !m){
m=Number(line)
}
else if(m){
let tokens=line.split(" ")
ways.push(tokens)
}
}
// console.log(names,ways,map)
let g=new Map()
for(const n of names){
g.set(n,[])
}
for(const w of ways){
let s1=w[0],s2=w[1]
g.get(s1).push(s2)
g.get(s2).push(s1)
}
let vis=new Set()
let topsum=0
let topname=''
let topn
let topw=0
let topweight
let sum=0
for(const n of names){
if(vis.has(n)) continue
const stack=[n]
vis.add(n)
while(stack.length){
let t=stack.pop()
let neigh=g.get(t)
for(const nei of neigh){
if(!vis.has(nei)){
vis.add(nei)
stack.push(nei)
}
}
let weight=map.get(t)
sum+=weight
if(weight>topw){
topw=weight
topn=t
}
}
if(sum>topsum){
topsum=sum
topname=topn
topweight=topw
}
sum=0
topw=0
topn=''
}
console.log(topname,topsum)
}()
