μμ μ λ ¬(Topological Sort)
μμ μ λ ¬μ μμκ° μ ν΄μ Έ μλ μμ μ μ°¨λ‘λ‘ μνν΄μΌ ν λ κ·Έ μμλ₯Ό κ²°μ ν΄μ£ΌκΈ° μν μκ³ λ¦¬μ¦μ΄λ€.
- μ¬λ¬ κ°μ λ΅μ΄ μ‘΄μ¬ν μ μλ€.
- DAG(Directed Acyclic Graph)μλ§ μ μ©μ΄ κ°λ₯νλ€.
- μ€νκ³Ό νλ‘ κ΅¬νλλ€.
κΈ°λ³Έ μ리
- μ§μ μ°¨μκ° 0μΈ μ μ μ νμ μ½μ νλ€.
- νμμ μμλ₯Ό κΊΌλ΄ μ°κ²°λ λͺ¨λ κ°μ μ μ κ±° ν μ§μ μ°¨μκ° 0μ΄ λ μ μ μ νμ μ½μ νλ€.
- νκ° λΉ λκΉμ§ 2λ² κ³Όμ μ λ°λ³΅νλ€.
- λͺ¨λ μμλ₯Ό λ°©λ¬ΈνκΈ° μ μ νκ° λΉλ€λ©΄ μ¬μ΄ν΄μ΄ μ‘΄μ¬νλ κ²μ΄κ³ , λͺ¨λ μμλ₯Ό λ°©λ¬Ένλ€λ©΄ νμμ κΊΌλΈ μμκ° μμ μ λ ¬μ κ²°κ³Όμ΄λ€.
λ¬Έμ
https://www.acmicpc.net/problem/1766
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
int main()
{
cin.tie(NULL);
cout.tie(NULL);
ios_base::sync_with_stdio(false);
int n, m;
cin >> n >> m;
vector<int> graph[32001];
vector<int> degree(n + 1, 0);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a].push_back(b);
degree[b]++;
}
priority_queue<int, vector<int>, greater<int>> pq;
for (int i = 1; i <= n; i++)
if (degree[i] == 0)
pq.push(i);
while (!pq.empty()) {
int top = pq.top();
cout << top << ' ';
pq.pop();
for (int i : graph[top]) {
degree[i]--;
if (degree[i] == 0)
pq.push(i);
}
}
}
https://www.acmicpc.net/problem/3665
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
int main()
{
cin.tie(NULL);
cout.tie(NULL);
ios_base::sync_with_stdio(false);
int t;
cin >> t;
while (t--) {
int n, m;
cin >> n;
int lastYearScore[501]{};
for (int i = 0; i < n; i++)
cin >> lastYearScore[i];
bool graph[501][501]{};
int degree[501]{};
for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++) {
graph[lastYearScore[i]][lastYearScore[j]] = true;
degree[lastYearScore[j]]++;
}
cin >> m;
while (m--) {
int a, b;
cin >> a >> b;
if (graph[a][b]) {
graph[b][a] = true;
graph[a][b] = false;
degree[a]++;
degree[b]--;
}
else {
graph[a][b] = true;
graph[b][a] = false;
degree[a]--;
degree[b]++;
}
}
queue<int> q;
for (int i = 1; i <= n; i++)
if (degree[i] == 0)
q.push(i);
vector<int> answer;
while (!q.empty()) {
int f = q.front();
q.pop();
answer.push_back(f);
for (int i = 1; i <= n; i++) {
if (graph[f][i]) {
degree[i]--;
if (degree[i] == 0)
q.push(i);
}
}
}
if (answer.size() == n) {
for (int j = 0; j < n; j++)
cout << answer[j] << ' ';
cout << endl;
}
else
cout << "IMPOSSIBLE" << endl;
}
}