-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path26_Topology Sort.cpp
60 lines (55 loc) Β· 1.21 KB
/
26_Topology Sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <vector>
#include <queue>
#define MAX 10
using namespace std;
int n, inDegree[MAX];
vector<int> a[MAX];
void topologySort(){
int result[MAX];
queue<int> q;
// μ§μ
μ°¨μκ° 0μΈ λ
Έλλ₯Ό νμ μ½μ
for(int i=1;i<=n;i++){
if(inDegree[i] == 0) q.push(i);
}
// μμμ λ ¬μ΄ μμ ν μνλλ €λ©΄ μ νν Nκ°μ λ
Έλλ₯Ό λ°©λ¬Έ
for(int i=1;i<=n;i++){
// nκ°λ₯Ό λ°©λ¬ΈνκΈ° μ μ νκ° λΉλ€λ©΄ μ¬μ΄ν΄μ΄ λ°μν κ²μ
λλ€.
if(q.empty()){
cout<<"μ¬μ΄ν΄ λ°μ";
return;
}
int x = q.front();
q.pop();
result[i] = x;
for(int j=0;j<a[x].size();j++){
int y = a[x][j];
// μλ‘κ² μ§μ
μ°¨μκ° 0μ΄ λ μ μ μ νμ μ½μ
ν©λλ€.
if(--inDegree[y] == 0){
q.push(y);
}
}
}
for(int i=1;i<=n;i++){
cout<<result[i]<<' ';
}
}
int main(void){
n = 7;
a[1].push_back(2);
inDegree[2]++;
a[1].push_back(5);
inDegree[5]++;
a[2].push_back(3);
inDegree[3]++;
a[3].push_back(4);
inDegree[4]++;
a[4].push_back(6);
inDegree[6]++;
a[5].push_back(6);
inDegree[6]++;
a[6].push_back(7);
inDegree[7]++;
topologySort();
}
// μ€νκ²°κ³Ό : 1 2 5 3 4 6 7