-
Notifications
You must be signed in to change notification settings - Fork 0
/
topsort.cpp
134 lines (97 loc) · 2.14 KB
/
topsort.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <limits.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <iostream>
#include <vector>
#include <queue>
#include <map>
#include <string>
#include <algorithm>
#include <bitset>
//#include <unordered_map>
using namespace std;
typedef pair<int, int> ii;
#define traverse(c, it) \
for (vector<ii>::iterator it = c.begin(); it != c.end(); it++)
int N, M;
vector<int> value;
//orientat
vector<vector<ii> > AdjList;
vector<ii> nodes;
vector<bool> visited;
vector<int> topoOrder;
priority_queue<ii, vector<ii>, greater<ii> > pq;
vector<int> inDegree;
void dfs(int node) {
visited[node] = true;
cout << node + 1 << " ";
traverse(AdjList[node], it) {
int next = it->second;
if(!visited[next]) {
inDegree[next]--;
//cout << inDegree[next] << endl;
if(inDegree[next] == 0) {
pq.push(make_pair(value[next], next));
}
}
}
if(!pq.empty()) {
ii next = pq.top();
pq.pop();
dfs(next.second);
}
}
void setup() {
//pq.clear();
for(int i = 0; i < N; i++) {
if(inDegree[i] == 0) {
//cout << i+1 << endl;
pq.push(make_pair(value[i], i));
}
}
}
void topoSort() {
visited.clear();
visited.resize(N, false);
setup();
ii start = pq.top();
pq.pop();
visited[start.second] = true;
dfs(start.second);
cout << endl;
}
bool cmp1(ii dest1, ii dest2) {
if(dest1.second <= dest2.second) {
return true;
}
return false;
}
bool cmp2(ii dest1, ii dest2) {
if(dest1.second >= dest2.second) {
return true;
}
return false;
}
int main() {
cin >> N >> M;
value.clear();
value.resize(N);
inDegree.clear();
inDegree.resize(N, 0);
for(int i = 0; i < N; i++) {
cin >> value[i];
}
AdjList.clear();
AdjList.resize(N);
int start, end;
for(int i = 0; i < M; i++) {
cin >> start >> end;
start--; end--;
inDegree[end]++;
AdjList[start].push_back(make_pair(value[end], end));
}
topoSort();
return 0;
}