Created
August 12, 2016 05:26
-
-
Save oskimura/75d819e7ed524355fa7105d7dceaa4d9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#include <vector> | |
#include <queue> | |
#include <list> | |
#include <iostream> | |
using namespace std; | |
typedef pair<int,int> ii; | |
void addEdge(list<int> *adj,int u, int v) | |
{ | |
adj[u].push_back(v); | |
} | |
template <int N> | |
void tsort(list<int> *adj) | |
{ | |
vector<int> in(N,0); | |
for (int u=0;u<N;u++) { | |
list<int>::iterator itr; | |
for (itr = adj[u].begin(); itr != adj[u].end();itr++) { | |
in[*itr]++; | |
} | |
} | |
queue<int> q; | |
for (int i=0;i<N;i++) { | |
if (in[i] == 0) { | |
q.push(i); | |
} | |
} | |
vector<int> result; | |
int cnt=0; | |
while(!q.empty()) { | |
int u = q.front(); | |
q.pop(); | |
result.push_back(u); | |
list<int>::iterator itr; | |
for (itr = adj[u].begin();itr != adj[u].end();itr++) { | |
if (--in[*itr] == 0) { | |
q.push(*itr); | |
} | |
} | |
cnt++; | |
} | |
for (int i=0; i<result.size(); i++) { | |
cout << result[i] << " "; | |
} | |
cout << endl; | |
} | |
int main() | |
{ | |
list<int> adj[6]; | |
addEdge(adj,5,2); | |
addEdge(adj,5,0); | |
addEdge(adj,4,0); | |
addEdge(adj,4,1); | |
addEdge(adj,2,3); | |
addEdge(adj,3,1); | |
tsort<6>(adj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment