Skip to content

Commit 21ce446

Browse files
committed
851. Loud and Rich
1 parent d00f739 commit 21ce446

1 file changed

Lines changed: 69 additions & 0 deletions

File tree

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
/*
2+
3+
1. 아이디어 : 각 노드기준 더 돈이 많거나 같은 노드의 집합에서 가장 quiet값이 작은 인덱스 선택
4+
dag구조 활용, 방향이 있고 cycle이 없는 그래프이므로, 위상정렬 사용 가능
5+
각 노드별로 더 작은 값들을 연결, 이때 각 노드의 degree(더 큰 값의 개수)를 같이 구해 degree가 0인 노드 파악
6+
큰 -> 작 순으로 그래프를 탐색하므로, 매 이동마다 가장 최선의값을 줄 수 있음
7+
8+
이때 degree[i] == 0인값만 deque에 넣는 이유는, 현 노드 기준 더 큰 모든 노드의 최적값을 계산해야 하기 때문
9+
10+
11+
2. 시간복잡도 : O(V + E)
12+
13+
3. 자료구조/알고리즘 : bfs + 위상정렬
14+
15+
*/
16+
17+
18+
class Solution {
19+
20+
private List<List<Integer>> dag = new ArrayList<>();
21+
private int[] ans;
22+
private int[] degree;
23+
24+
public int[] loudAndRich(int[][] richer, int[] quiet) {
25+
// richer[0]>richer[1]
26+
// ans[x] = y
27+
// y는 x보다 돈이 같거나 많은 그룹(본인 포함), 그중 quite가 가장 작아야함
28+
29+
// graph 구조 , 사이클 없음, 단방향 -> DAG
30+
31+
ans = new int[quiet.length];
32+
degree = new int[quiet.length];
33+
34+
for(int i=0; i<quiet.length; i++) {
35+
dag.add(new ArrayList<>());
36+
}
37+
38+
for(int[] r : richer) {
39+
dag.get(r[0]).add(r[1]);
40+
degree[r[1]]++;
41+
}
42+
43+
bfs(quiet);
44+
45+
return ans;
46+
}
47+
48+
void bfs(int[] quiet) {
49+
Deque<Integer> dq = new ArrayDeque<>();
50+
51+
for(int i=0; i<quiet.length; i++) {
52+
if(degree[i] == 0) dq.add(i);
53+
ans[i] = i;
54+
}
55+
56+
while(!dq.isEmpty()) {
57+
58+
int cur = dq.poll();
59+
60+
for(int node : dag.get(cur)) {
61+
62+
if(quiet[ans[cur]]<quiet[ans[node]]) ans[node] = ans[cur];
63+
degree[node]--;
64+
65+
if(degree[node] == 0) dq.add(node);
66+
}
67+
}
68+
}
69+
}

0 commit comments

Comments
 (0)