-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1022.cpp
More file actions
51 lines (39 loc) · 883 Bytes
/
1022.cpp
File metadata and controls
51 lines (39 loc) · 883 Bytes
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
#include <bits/stdc++.h>
using namespace std;
vector<int> deg;
vector<vector<int>> g;
vector<int> topological_sort(vector<int> deg, vector<vector<int> > g, int n) {
vector<int> result;
stack<int> s;
for(int i = 0; i < n; i++) {
if(!deg[i]) s.push(i);
}
while(!s.empty()) {
int v = s.top();
result.push_back(v);
s.pop();
for(int i = 0; i < g[v].size(); i++) {
int to = g[v][i];
deg[to]--;
if(!deg[to]) s.push(to);
}
}
return result;
}
main()
{
int n;
cin >> n;
g.resize(n);
deg.resize(n);
for(int i = 0; i < n; i++) {
int x;
while(cin>>x && x) {
x--;
g[i].push_back(x);
deg[x]++;
}
}
auto result = topological_sort(deg,g,n);
for(int i = 0; i < n; i++) cout << result[i]+1 << " ";
}