From fe61ae5b3697c1e0fd9448a2f16f3ad16fa7d2ea Mon Sep 17 00:00:00 2001 From: bomik0221 Date: Sun, 18 Feb 2024 23:10:59 +0900 Subject: [PATCH] =?UTF-8?q?240218=20=EB=AC=B8=EC=A0=9C=EC=A7=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../240218.cpp" | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 "bomik0221/\352\267\270\353\236\230\355\224\204/240218.cpp" diff --git "a/bomik0221/\352\267\270\353\236\230\355\224\204/240218.cpp" "b/bomik0221/\352\267\270\353\236\230\355\224\204/240218.cpp" new file mode 100644 index 0000000..ff3905d --- /dev/null +++ "b/bomik0221/\352\267\270\353\236\230\355\224\204/240218.cpp" @@ -0,0 +1,51 @@ +#include +#include +#include + +int main() { + int N, M; + std::cin >> N >> M; + + std::vector> graph(N + 1, std::vector(0, 0)); + std::vector indegree(N + 1, 0); + std::vector sorted; + + //그래프 입력 받기 + for (int i = 0; i < M; i++) { + int a, b; + std::cin >> a >> b; + graph[a].push_back(b); + indegree[b]++; + } + + //위상정렬의 초기 상태 + std::queue q; + for (int i = 1; i < N + 1; i++) { + if (indegree[i] == 0) { + q.push(i); + break; //쉬운 문제는 먼저 출력하라는 조건이 있으므로 큐에 문제 하나가 들어오면 바로 다음 과정으로 넘어가야함. + } + } + //위상정렬 진행 + while (!q.empty()) { + int temp = q.front(); + sorted.push_back(temp); + q.pop(); + indegree[temp] = -1; + for (auto next_node : graph[temp]) { + indegree[next_node]--; + } + for (int i = 1; i < N + 1; i++) { + if (indegree[i] == 0) { + q.push(i); + break; + } + } + } + + //답 출력 + for (int i = 0; i < sorted.size(); i++) { + std::cout << sorted[i] << " "; + } + return 0; +} \ No newline at end of file