[BOJ] 2623λ² | μμ
νλ‘κ·Έλ¨ (C++)
2023. 12. 19. 15:48γCoding Test/BOJ
πλ¬Έμ 보λ¬κ°κΈ°
π§π»νμ΄ κ³Όμ
μμ μ λ ¬μ μ¬μ©ν΄ ν μ μλ λ¬Έμ μΈλ°, μ¬μ΄ν΄(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
λ°μν
'Coding Test > 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 |