๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 14567๋ฒˆ - ์„ ์ˆ˜๊ณผ๋ชฉ

by dkswnkk 2021. 11. 11.

๋ฌธ์ œ

 

14567๋ฒˆ: ์„ ์ˆ˜๊ณผ๋ชฉ (Prerequisite)

3๊ฐœ์˜ ๊ณผ๋ชฉ์ด ์žˆ๊ณ , 2๋ฒˆ ๊ณผ๋ชฉ์„ ์ด์ˆ˜ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” 1๋ฒˆ ๊ณผ๋ชฉ์„ ์ด์ˆ˜ํ•ด์•ผ ํ•˜๊ณ , 3๋ฒˆ ๊ณผ๋ชฉ์„ ์ด์ˆ˜ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” 2๋ฒˆ ๊ณผ๋ชฉ์„ ์ด์ˆ˜ํ•ด์•ผ ํ•œ๋‹ค.

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <queue>

using namespace std;
int N, M; //N=๊ณผ๋ชฉ์˜ ์ˆ˜, M=์„ ์ˆ˜ ์กฐ๊ฑด์˜ ์ˆ˜
int indegree[500001];    //๋ชจ๋“  ๋…ธ๋“œ์— ๋Œ€ํ•œ ์ง„์ž…์ฐจ์ˆ˜๋Š” 0์œผ๋กœ ์ดˆ๊ธฐํ™”
vector<int>graph[500001];    //๊ฐ ๋…ธ๋“œ์— ์—ฐ๊ฒฐ๋œ ๊ฐ„์„  ์ •๋ณด๋ฅผ ๋‹ด๊ธฐ ์œ„ํ•œ ์—ฐ๊ฒฐ๋ฆฌ์ŠคํŠธ ์ดˆ๊ธฐํ™”
int result[500001];    //์œ„์ƒ์ •๋ ฌ ์ˆ˜ํ–‰๊ฒฐ๊ณผ๋ฅผ ๋‹ด์„ ๋ฆฌ์ŠคํŠธ


void topologySort() {
    queue<int>q;

    for (int i = 1; i <= N; i++) {    //์ฒ˜์Œ์—๋Š” ์ง„์ž…์ฐจ์ˆ˜๊ฐ€ 0์ธ ๋…ธ๋“œ๋ฅผ ํ์— ์‚ฝ์ž…
        if (indegree[i] == 0) {
            q.push(i);
            result[i] = 1;    //ํ•ด๋‹น ๊ณผ๋ชฉ ์€ ๋ฐ”๋กœ ๋“ค์„ ์ˆ˜ ์žˆ์Œ.
        }
    }
    while (!q.empty()) {    //ํ๊ฐ€ ๋นŒ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต
        int now = q.front();
        q.pop();

        for (int i = 0; i < graph[now].size(); i++) {    //ํ•ด๋‹น ์›์†Œ์™€ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ๋“ค์˜ ์ง„์ž…์ฐจ์ˆ˜์—์„œ 1๋นผ๊ธฐ
            indegree[graph[now][i]] -= 1;
            if (indegree[graph[now][i]] == 0) {
                q.push(graph[now][i]);    //์ƒˆ๋กญ๊ฒŒ ์ง„์ž…์ฐจ์ˆ˜๊ฐ€ 0์ด๋˜๋Š” ๋…ธ๋“œ๋ฅผ ํ์— ์‚ฝ์ž…
                result[graph[now][i]] = result[now] + 1;
            }
        }
    }

    for (int i = 1; i <= N; i++) {    //์œ„์ƒ ์ •๋ ฌ์„ ์ˆ˜ํ–‰ํ•œ ๊ฒฐ๊ณผ ์ถœ๋ ฅ
        cout << result[i] << ' ';
    }
}
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cin >> N >> M;
    for (int i = 0; i < M; i++) {
        int a, b; cin >> a >> b;
        graph[a].push_back(b);    //์ •์  A์—์„œ B๋กœ ์ด๋™๊ฐ€๋Šฅ
        indegree[b] += 1;    //์ง„์ž… ์ฐจ์ˆ˜๋ฅผ 1 ์ฆ๊ฐ€
    }
    topologySort();
}

 

ํ’€์ด

๋‹จ์ˆœ ์œ„์ƒ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ˆ˜ํ–‰ํ•˜๋ฉด ๋˜๋Š” ๋ฌธ์ œ์˜€์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€