[BOJ] 1766๋ฒˆ | ๋ฌธ์ œ์ง‘ (C++)

2023. 12. 19. 14:22ใ†Coding Test/BOJ

๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

1766๋ฒˆ: ๋ฌธ์ œ์ง‘

์ฒซ์งธ ์ค„์— ๋ฌธ์ œ์˜ ์ˆ˜ N(1 ≤ N ≤ 32,000)๊ณผ ๋จผ์ € ํ‘ธ๋Š” ๊ฒƒ์ด ์ข‹์€ ๋ฌธ์ œ์— ๋Œ€ํ•œ ์ •๋ณด์˜ ๊ฐœ์ˆ˜ M(1 ≤ M ≤ 100,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ M๊ฐœ์˜ ์ค„์— ๊ฑธ์ณ ๋‘ ์ •์ˆ˜์˜ ์ˆœ์„œ์Œ A,B๊ฐ€ ๋นˆ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ

www.acmicpc.net

 

๐Ÿง‘‍๐Ÿ’ปํ’€์ด ๊ณผ์ •

 

์œ„์ƒ ์ •๋ ฌ(Topological Sort)์— ๋Œ€ํ•ด ๊ณต๋ถ€ํ•œ ํ›„, ํ’€์–ด๋ณด๋ ค๊ณ  ๊ณจ๋ž๋˜ ๋ฌธ์ œ ์ค‘ ํ•˜๋‚˜์ž…๋‹ˆ๋‹ค. ์œ„์ƒ ์ •๋ ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ทธ๋Œ€๋กœ ์ ์šฉํ•˜๋˜, ์‰ฌ์šด ๋ฌธ์ œ๋ถ€ํ„ฐ ํ’€์–ด์•ผ ํ•˜๋‹ˆ ์šฐ์„ ์ˆœ์œ„ ํ(Priority Queue)๋ฅผ ๋Œ€์‹  ์‚ฌ์šฉํ•ด์ฃผ๋ฉด ๋์ธ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ์ด ์™ธ์—๋Š” ๋” ์ด์ƒ ์„ค๋ช…ํ•  ๋‚ด์šฉ์ด ์ง„์งœ๋กœ ์—†๊ธฐ์—, ์•„๋ž˜์— ์ฝ”๋“œ๋ฅผ ์ฒจ๋ถ€ํ•˜๋„๋ก ํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

 

โœ๏ธ์†Œ์Šค ์ฝ”๋“œ ๋ฐ ๊ฒฐ๊ณผ

#include <iostream>
#include <vector>
#include <queue>

using namespace std;
#define FAST_IO ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL);

vector<int> GetSolvedOrder(const vector<vector<int>>& graph, vector<int>& inDegrees, int N) {
    priority_queue<int, vector<int>, greater<int>> problems;
    for (int i = 1; i <= N; i++) {
        if (inDegrees[i] == 0)
            problems.push(i);
    }

    vector<int> answers(N + 1);
    for (int i = 1; i <= N; i++) {
        
        int problem = problems.top();
        problems.pop();
        answers[i] = problem;

        for (const auto& other : graph[problem]) {
            if (--inDegrees[other] == 0)
                problems.push(other);
        }
    }

    return answers;
}

int main() {
    FAST_IO
    int N, M;
    cin >> N >> M;

    int from, to;
    vector<vector<int>> graph(N + 1, vector<int>());
    vector<int> inDegrees(N + 1, 0);

    for (int i = 0; i < M; i++) {
        cin >> from >> to;
        graph[from].emplace_back(to);
        inDegrees[to]++;
    }

    vector<int> answers = GetSolvedOrder(graph, inDegrees, N);
    for (int i = 1; i <= N; i++)
        cout << answers[i] << " ";
    
    return 0;
}

 

 

728x90
๋ฐ˜์‘ํ˜•