728x90
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ปํ์ด ๊ณผ์
์์ ์ ๋ ฌ์ ์ฌ์ฉํด ํ ์ ์๋ ๋ฌธ์ ์ธ๋ฐ, ์ฌ์ดํด(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
๋ฐ์ํ
'๐คAlgorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 2637๋ฒ | ์ฅ๋๊ฐ ์กฐ๋ฆฝ (C++) (0) | 2023.12.21 |
---|---|
[BOJ] 11779๋ฒ | ์ต์๋น์ฉ ๊ตฌํ๊ธฐ 2 (C++) (1) | 2023.12.20 |
[BOJ] 1516๋ฒ | ๊ฒ์ ๊ฐ๋ฐ (C++) (1) | 2023.12.19 |
[BOJ] 1766๋ฒ | ๋ฌธ์ ์ง (C++) (0) | 2023.12.19 |
[BOJ] 1074๋ฒ | Z (C++) (0) | 2023.12.18 |