๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ
728x90
๐Ÿ”—๋ฌธ์ œ ๋ณด๋Ÿฌ๊ฐ€๊ธฐ
 

2623๋ฒˆ: ์Œ์•…ํ”„๋กœ๊ทธ๋žจ

์ฒซ์งธ ์ค„์—๋Š” ๊ฐ€์ˆ˜์˜ ์ˆ˜ N๊ณผ ๋ณด์กฐ PD์˜ ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ€์ˆ˜๋Š” ๋ฒˆํ˜ธ 1, 2,…,N ์œผ๋กœ ํ‘œ์‹œํ•œ๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ ๊ฐ ๋ณด์กฐ PD๊ฐ€ ์ •ํ•œ ์ˆœ์„œ๋“ค์ด ํ•œ ์ค„์— ํ•˜๋‚˜์”ฉ ๋‚˜์˜จ๋‹ค. ๊ฐ ์ค„์˜ ๋งจ ์•ž์—๋Š” ๋ณด์กฐ PD๊ฐ€ ๋‹ด๋‹นํ•œ

www.acmicpc.net

 

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

 

์œ„์ƒ ์ •๋ ฌ์„ ์‚ฌ์šฉํ•ด ํ’€ ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ธ๋ฐ, ์‚ฌ์ดํด(Cycle) ๊ฐ์ง€ ์กฐ๊ฑด์„ ํ•˜๋‚˜ ๋” ๋„ฃ์–ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ์ˆœ์„œ๋ฅผ ์ •ํ•˜๋Š” ๊ฒŒ ๋ถˆ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ๋Š” ๊ฐ ๊ฐ€์ˆ˜๋“ค์˜ ์ˆœ์„œ์— ์‚ฌ์ดํด์ด ์žˆ๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. ์ด๋Š” ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ๋Œ๊ธฐ ์ „์— ํ(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> Solution(const vector<vector<int>>& graph, vector<int>& inDegrees, int N) {
    vector<int> answers(N + 1);
    queue<int> nextSingers;

    for (int i = 1; i <= N; i++)
        if (inDegrees[i] == 0)
            nextSingers.push(i);
    
    for (int i = 1; i <= N; i++) {
        if (nextSingers.empty())
            return {0, 0};
        
        int singer = nextSingers.front();
        answers[i] = singer;
        nextSingers.pop();

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

    return answers;
}

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

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

    for (int i = 0; i < M; i++) {
        cin >> singerCount;
        int from, to;

        for (int i = 0; i < singerCount; i++) {
            cin >> to;

            if (i == 0) {
                from = to;
                continue;
            }

            graph[from].emplace_back(to);
            inDegrees[to]++;
            from = to;
        }
    }

    vector<int> answers = Solution(graph, inDegrees, N);
    for (int i = 1; i < answers.size(); i++)
        cout << answers[i] << "\n";

    return 0;
}

 

 

728x90
๋ฐ˜์‘ํ˜•