[BOJ] 1766๋ฒ | ๋ฌธ์ ์ง (C++)
2023. 12. 19. 14:22ใCoding Test/BOJ
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐ง๐ปํ์ด ๊ณผ์
์์ ์ ๋ ฌ(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
๋ฐ์ํ
'Coding Test > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 2623๋ฒ | ์์ ํ๋ก๊ทธ๋จ (C++) (1) | 2023.12.19 |
---|---|
[BOJ] 1516๋ฒ | ๊ฒ์ ๊ฐ๋ฐ (C++) (1) | 2023.12.19 |
[BOJ] 1074๋ฒ | Z (C++) (0) | 2023.12.18 |
[BOJ] 1916๋ฒ | ์ต์๋น์ฉ ๊ตฌํ๊ธฐ (C++) (0) | 2023.12.13 |
[BOJ] 1987๋ฒ | ์ํ๋ฒณ (C++) (0) | 2023.12.13 |