Created
December 6, 2012 23:52
-
-
Save agasiev/4229517 to your computer and use it in GitHub Desktop.
Topological sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using namespace std; | |
vector<vector<int> > g; | |
vector<bool> used; | |
vector<int> result; | |
void dfs(int n) { | |
used[n] = true; | |
for (int i = 0; i < g[n].size(); i++) { | |
if (!used[g[n][i]]) { | |
dfs(g[n][i]); | |
} | |
} | |
result.push_back(n); | |
} | |
void topological_sort() { | |
for (int i = 0; i < used.size(); i++) | |
used[i] = false; | |
for (int i = 0; i < g.size(); i++) { | |
if (!used[i]) | |
dfs(i); | |
} | |
std::reverse(result.begin(), result.end()); | |
} | |
int main(int argc, char ** argv) { | |
/* | |
Sample input: | |
5 | |
1 1 | |
0 | |
3 1 3 4 | |
1 0 | |
0 | |
*/ | |
int node_cnt = 0; | |
cin >> node_cnt; | |
g.resize(node_cnt); | |
used.resize(node_cnt); | |
for (int i = 0; i < node_cnt; i++) { | |
int to_cnt = 0; | |
cin >> to_cnt; | |
g[i].resize(to_cnt); | |
for (int j = 0; j < to_cnt; j++) { | |
cin >> g[i][j]; | |
} | |
} | |
topological_sort(); | |
for (int i = 0; i < result.size(); i++) { | |
cout << result[i] << " "; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment