๐ ๋ฌธ์
๐ ์์ด๋์ด
๋จ์ํ ์์์ ๋ ฌ ๋ฌธ์ ์ ๋๋ค.
๊ณผ๊ฑฐ์ ๋ค๋ฅธ ๋ธ๋ก๊ทธ์ ์์ฑํ ๊ธ์ ๋๋ค.
๐ ํ์ด
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class boj_14567_์ ์๊ณผ๋ชฉ {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
List<List<Integer>> outGraph = new ArrayList<>();
for (int i = 0; i < n; i++) {
outGraph.add(new ArrayList<>());
}
int[] inDegree = new int[n];
int[] semesters = new int[n];
while (m-->0){
st = new StringTokenizer(br.readLine());
int start = Integer.parseInt(st.nextToken()) - 1;
int end = Integer.parseInt(st.nextToken()) - 1;
outGraph.get(start).add(end); //ํ์ ๊ณผ๋ชฉ ์ถ๊ฐ
inDegree[end]++; //์ ์ ๊ณผ๋ชฉ์ด ์๋ ๊ฒฝ์ฐ ์ถ๊ฐ
}
//topological sort ์์์ ๋ ฌ ๊ณผ์
Queue<Integer> queue = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (inDegree[i] == 0) queue.add(i);
}
int semester = 0;
while (!queue.isEmpty()) {
int size = queue.size();
semester++;
for (int i = 0; i < size; i++) {
int now = queue.poll();
semesters[now] = semester;
for (Integer next : outGraph.get(now)) {
inDegree[next]--;
if (inDegree[next] == 0) queue.add(next);
}
}
}
//output
for (int i : semesters) {
sb.append(i).append(" ");
}
System.out.println(sb);
}
}
'๋ฐฑ์ค(boj)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA]13904 ๊ณผ์ , greedy , ๊ณจ๋3 (0) | 2023.06.24 |
---|---|
[JAVA]1002 ํฐ๋ , ๋ด์ ๊ณผ ์ธ์ (0) | 2023.06.23 |
[JAVA]14676 ์์ฐ๋ ์ฌ๊ธฐ๊พผ? ์์์ ๋ ฌ ๊ณจ๋3 (0) | 2023.06.15 |
[JAVA]17299 ์ค๋ฑํฐ์(๊ณจ๋3, ์คํ) (0) | 2023.06.12 |
[JAVA]1958 LCS3(dp, ๊ณจ๋3) (0) | 2023.06.08 |