PS/๋ฐฑ์ค
[๋ฐฑ์ค] 2252 : ์ค ์ธ์ฐ๊ธฐ - java [์๋ฐ]
mokhs
2022. 2. 27. 12:06
https://www.acmicpc.net/problem/2252
2252๋ฒ: ์ค ์ธ์ฐ๊ธฐ
์ฒซ์งธ ์ค์ N(1 ≤ N ≤ 32,000), M(1 ≤ M ≤ 100,000)์ด ์ฃผ์ด์ง๋ค. M์ ํค๋ฅผ ๋น๊ตํ ํ์์ด๋ค. ๋ค์ M๊ฐ์ ์ค์๋ ํค๋ฅผ ๋น๊ตํ ๋ ํ์์ ๋ฒํธ A, B๊ฐ ์ฃผ์ด์ง๋ค. ์ด๋ ํ์ A๊ฐ ํ์ B์ ์์ ์์ผ ํ๋ค๋ ์
www.acmicpc.net
ํ์ด
- "์ฐ๊ฒฐ ์ ๋ณด๊ฐ ์ฃผ์ด์ง N๋ช
์ ํ์ ์ค ์ธ์ฐ๊ธฐ"๋ ๋ค์๊ณผ ๊ฐ์ด ํด์ํ ์ ์๋ค.
=> ์ฐ๊ฒฐ ์ ๋ณด๊ฐ ์ฃผ์ด์ง ์ํํ์ง ์๋ ๋ฐฉํฅ์ฑ ๊ทธ๋ํ(DAG=๋ฐฉํฅ์ฑ ๋น์ํ ๊ทธ๋ํ)์์ ๊ฐ ๋ ธ๋๋ฅผ ์ค ์ธ์ฐ์์ค. - ์ด๋ฅผ ๊ตฌํ๋ ๋ฐฉ๋ฒ์ ์์์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ๊ณผ ์ผ์นํ๋ฏ๋ก ์์์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ์ ์ด์ฉํด ํ์ดํ๋ค.
- ์ฌ๊ธฐ์๋ ๊ฐ ๋ ธ๋์ ์ฐ๊ฒฐ ๋นํ ์ ๋ณด๋ฅผ linked ๋ฐฐ์ด์ ๋ฏธ๋ฆฌ ์ ๋ ฅ ํ linked ๋ฐฐ์ด์ด 0์ธ ๊ฒฝ์ฐ ํด๋น ๋ ธ๋๋ฅผ queue์ ์ถ๊ฐํ์ฌ BFS๋ฅผ ์ด์ฉํด ์์์ ๋ ฌ ์๊ณ ๋ฆฌ์ฆ์ ๊ตฌํํ๋ค.
- ๊ฐ ๋ ธ๋์ ์ฐ๊ฒฐ ๋นํ ์ ๋ณด๋ฅผ linked ๋ฐฐ์ด์ ์ ์ฅํ๋ค.
- linked ๋ฐฐ์ด์์ ๊ฐ์ด 0์ธ ๋ ธ๋๋ฅผ queue์ ์ถ๊ฐํ๋ค.
- ์ฌ๊ธฐ์๋ถํฐ๋ BFS๋ฅผ ์ด์ฉํด ํ์ํ๋๋ฐ, queue์ ๋
ธ๋๋ฅผ ์ถ๊ฐํ๋ ์กฐ๊ฑด์ ๋ค์๊ณผ ๊ฐ๋ค.
- queue์์ ๋ ธ๋ ํ๋๋ฅผ ๊บผ๋ด๊ณ ์ ๋ต ์ถ๋ ฅ์ ์ด์ฉํ StringBuffer์ ์ถ๊ฐํ๋ค.
- queue์์ ๊บผ๋ธ ํ์ฌ ๋ ธ๋(current)์ ์ฐ๊ฒฐ๋ ๋ ธ๋(node)๋ฅผ ์ํํ๋ฉฐ, linked[node]๋ฅผ 1์ฉ ๊ฐ์ ์ํจ๋ค.
- linked[node]๊ฐ 0์ด ๋์๋ค๋ฉด, queue์ ์ถ๊ฐํ๊ณ ๋ฐฉ๋ฌธ์ฒ๋ฆฌํ๋ค.
- ์ฌ๊ธฐ์ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ๋ linked[node] == 0 ์ธ ๊ฒฝ์ฐ๋ก ์ฒ๋ฆฌํ๋ค.
- StringBuffer์ ๋ด์๋ ๊ฒฐ๊ณผ๋ฅผ ์ถ๋ ฅํ๋ค.
์ฝ๋
import java.io.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class ์ค_์ธ์ฐ๊ธฐ_2252 {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
public static void main(String[] args) throws IOException {
String[] input = br.readLine().split(" ");
int N = Integer.parseInt(input[0]);
int M = Integer.parseInt(input[1]);
StringBuffer sb = new StringBuffer();
List<List<Integer>> graph = new ArrayList<>();
int[] linked = new int[N + 1];
for (int i = 0; i <= N; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < M; i++) {
String[] input2 = br.readLine().split(" ");
int start = Integer.parseInt(input2[0]);
int target = Integer.parseInt(input2[1]);
linked[target] += 1;
graph.get(start).add(target);
}
Queue<Integer> queue = new LinkedList<>();
for (int i = 1; i < linked.length; i++) {
if (linked[i] == 0) {
queue.add(i);
}
}
while (!queue.isEmpty()) {
Integer current = queue.poll();
sb.append(current + " ");
List<Integer> nodeList = graph.get(current);
for (Integer node : nodeList) {
if (--linked[node] == 0) {
queue.add(node);
}
}
}
bw.write(sb.toString());
bw.close();
br.close();
}
}