๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

[Algorithm/Java][๋ฐฑ์ค€] 2252๋ฒˆ ์ค„ ์„ธ์šฐ๊ธฐ

๋ฐ˜์‘ํ˜•

[BOJ] 2252๋ฒˆ ์ค„ ์„ธ์šฐ๊ธฐ

https://www.acmicpc.net/problem/2252

๋ฌธ์ œ ์ ‘๊ทผ

์œ„์ƒ ์ •๋ ฌ์„ ํ†ตํ•ด์„œ ์‰ฝ๊ฒŒ ํ‘ผ ๋ฌธ์ œ์ด๋‹ค.
์œ„์ƒ ์ •๋ ฌ์ด๋ž€ ์ˆœํ™˜์ด ์—†๋Š” ๊ทธ๋ž˜ํ”„์—์„œ ์ •์ ๊ฐ„์˜ ์ˆœ์„œ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด๋‹ค.
๊ฐ๊ฐ์˜ ํ•™์ƒ๋“ค์„ ์ •์ ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๊ณ , ์ž…๋ ฅ์œผ๋กœ ๋“ค์–ด์˜ค๋Š” ์ˆœ์„œ๋“ค์„ ๊ทธ๋ž˜ํ”„๋“ค์˜ ๊ฐ„์„ ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ์‰ฝ๊ฒŒ ๋ฌธ์ œ๊ฐ€ ํ’€๋ฆฐ๋‹ค.
์œ„์ƒ ์ •๋ ฌ์ด๋ž€ ์šฐ์„  ๋“ค์–ด์˜ค๋Š” ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” linkCnt์˜ ๊ฐ’์ด 0์ธ ์ •์ ๋“ค์„ ํ์— ๋„ฃ๊ณ , ํ•˜๋‚˜์”ฉ ํ์—์„œ ๋นผ๋ฉด์„œ ํ•ด๋‹น ์ •์ ๊ณผ ์—ฐ๊ฒฐ๋œ ์ •์ ๋“ค์— ๋Œ€ํ•ด์„œ linkCnt๋ฅผ -1 ํ•ด์ฃผ๊ณ  ๋‹ค์‹œ linkCnt์˜ ๊ฐ’์ด 0์ธ ์ •์ ๋“ค์„ ํ์— ๋„ฃ๋Š” ๋ฐฉ์‹์œผ๋กœ ์ง„ํ–‰๋œ๋‹ค.

Code

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class BOJ2252 {
    static int N;
    static int M;
    static int[] linkCnt;
    static ArrayList<ArrayList<Integer>> graph;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        N = sc.nextInt();
        M = sc.nextInt();
        linkCnt = new int[N + 1];
        graph = new ArrayList<>();
        for(int i = 0; i<=N; i++){
            graph.add(i, new ArrayList<>());
        }
        for(int i = 0; i<M; i++){
            int from = sc.nextInt();
            int to = sc.nextInt();
            graph.get(from).add(to);
            linkCnt[to]++;
        }
        System.out.println(topologicalSort());
    }
    public static String topologicalSort() {
        Queue<Integer> q = new LinkedList<>();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i <= N; i++) {
            if(linkCnt[i] == 0) q.offer(i);
        }
        while (!q.isEmpty()) {
            int cur = q.poll();
            for (int v : graph.get(cur)) {
                linkCnt[v] --;
                if(linkCnt[v] == 0) q.offer(v);
            }
            sb.append(cur).append(" ");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
๋ฐ˜์‘ํ˜•