
n명의 사람이 있고 각자 돈과 조용함(quiet)이 다르다. 돈은 직접 주지 않고 richer[i] = [a, b] 형태로 "a가 b보다 돈이 많다"는 관계만 준다. quiet[i]는 i번 사람의 조용함이고 값이 작을수록 조용하다.
각 사람 x에 대해 x보다 돈이 확실히 많거나 같은 사람들 중 가장 조용한 사람의 번호를 answer[x]에 담아 반환한다.
richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]]
quiet = [3,2,5,4,6,1,7,0]
answer = [5,5,2,5,4,5,6,7]
처음 읽으면 문장이 꼬여 있어서 잘 안 들어온다. 풀어 쓰면 이렇다.
richer를 "b → a" 간선으로 보면 b에서 출발해 도달할 수 있는 모든 노드가 "b보다 확실히 부자인 사람"이다.따라서 각 노드에서 도달 가능한 집합(자기 포함) 중 quiet 최소인 노드를 찾는 문제다. 사이클이 없다고 보장되니 DAG다.
const queue = [i];
while (queue.length) {
const target = queue.pop();
if (!graph.has(target)) { mostRich.push(target); continue; }
for (const rich of graph.get(target)) {
if (graph.has(rich)) queue.push(...graph.get(rich));
else mostRich.push(rich);
}
}
const answer = mostRich.toSorted((a, b) => quiet[a] - quiet[b])[0];
사람마다 BFS를 돌려 "더 부자가 없는 끝 노드"만 후보에 넣었다. 두 가지가 틀렸다.
핵심 식은 한 줄이다.
answer[x] = x 자신과, x보다 직접 부자인 각 y의 answer[y] 중 quiet가 가장 작은 사람
y의 답을 구해 두면 x에서 재활용할 수 있으니 메모이제이션이 자연스럽다.
여기서 세 번 더 틀렸다.
Array(n).fill([])로 인접 리스트를 만들었다. fill은 같은 배열 참조를 n칸에 복사하므로 모든 사람이 같은 목록을 공유한다. Array.from({ length: n }, () => [])로 바꿨다.quiet[curr] > quiet[i]로 썼다. 부등호가 반대였고, 고정값 quiet[i]가 아니라 지금까지의 최선과 비교해야 후보 여러 명 중 최소가 남는다.function loudAndRich(richer: number[][], quiet: number[]): number[] {
const personLen = quiet.length;
const richerThan = Array.from({ length: personLen }, () => []);
for (const [more, less] of richer) {
richerThan[less].push(more);
}
const memo = Array(personLen).fill(-1);
const findLoudest = (i: number) => {
if (memo[i] !== -1) return memo[i];
let mostLouder = i;
for (const richerIdx of richerThan[i]) {
const curr = findLoudest(richerIdx);
if (quiet[curr] < quiet[mostLouder]) mostLouder = curr;
}
return (memo[i] = mostLouder);
};
for (let i = 0; i < personLen; i++) findLoudest(i);
return memo;
}
Array(n).fill([])은 참조 공유다. 2차원 배열은 Array.from으로 만든다.