#include <iostream>
#include <vector>
#include <stack>
#include <utility>
using namespace std;
void rundfs(const vector<vector<int> >& graph, const int max) {
vector<bool> visited(max);
stack<pair<bool,int>> dfs;
stack<int> postOrder;
for(int i=0 ; i < max ; i++){
if(!visited[i]){
dfs.push(make_pair(false,i));
}
while(!dfs.empty()){
pair<bool,int> node=dfs.top();
dfs.pop();
if (node.first) {
cout << node.second << endl;
postOrder.push(node.second);
continue;
}
if (visited[node.second]) {
continue;
}
visited[node.second]=true;
dfs.push(make_pair(true, node.second));
const auto& newVec=graph[node.second]; //vector of neighboors
for(const auto son: newVec){
if(!visited[son]){
dfs.push(make_pair(false, son));
}
}
}
}
}
int main() {
rundfs({ {1, 2, 3}, {3}, {1, 3}, {}}, 4);
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8c3RhY2s+CiNpbmNsdWRlIDx1dGlsaXR5Pgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKdm9pZCBydW5kZnMoY29uc3QgdmVjdG9yPHZlY3RvcjxpbnQ+ID4mIGdyYXBoLCBjb25zdCBpbnQgbWF4KSB7CnZlY3Rvcjxib29sPiB2aXNpdGVkKG1heCk7CnN0YWNrPHBhaXI8Ym9vbCxpbnQ+PiBkZnM7CnN0YWNrPGludD4gcG9zdE9yZGVyOwpmb3IoaW50IGk9MCA7IGkgPCBtYXggOyBpKyspewogICAgaWYoIXZpc2l0ZWRbaV0pewogICAgICAgIGRmcy5wdXNoKG1ha2VfcGFpcihmYWxzZSxpKSk7CiAgICB9ICAgCiAgICB3aGlsZSghZGZzLmVtcHR5KCkpewogICAgICAgIHBhaXI8Ym9vbCxpbnQ+IG5vZGU9ZGZzLnRvcCgpOwogICAgICAgIGRmcy5wb3AoKTsKICAgICAgICBpZiAobm9kZS5maXJzdCkgewogICAgICAgIAljb3V0IDw8IG5vZGUuc2Vjb25kIDw8IGVuZGw7CiAgICAgICAgICAgIHBvc3RPcmRlci5wdXNoKG5vZGUuc2Vjb25kKTsKICAgICAgICAgICAgY29udGludWU7CiAgICAgICAgfQogICAgICAgIGlmICh2aXNpdGVkW25vZGUuc2Vjb25kXSkgewogICAgICAgIAljb250aW51ZTsKICAgICAgICB9CiAgICAgICAgdmlzaXRlZFtub2RlLnNlY29uZF09dHJ1ZTsKICAgICAgICBkZnMucHVzaChtYWtlX3BhaXIodHJ1ZSwgbm9kZS5zZWNvbmQpKTsKICAgICAgICBjb25zdCBhdXRvJiBuZXdWZWM9Z3JhcGhbbm9kZS5zZWNvbmRdOyAvL3ZlY3RvciBvZiBuZWlnaGJvb3JzCiAgICAgICAgZm9yKGNvbnN0IGF1dG8gc29uOiBuZXdWZWMpewogICAgICAgICAgICBpZighdmlzaXRlZFtzb25dKXsKICAgICAgICAgICAgICAgIGRmcy5wdXNoKG1ha2VfcGFpcihmYWxzZSwgc29uKSk7CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICB9Cn0KCn0KCmludCBtYWluKCkgewoJcnVuZGZzKHsgezEsIDIsIDN9LCAgIHszfSwgICB7MSwgM30sICAge319LCA0KTsKCXJldHVybiAwOwp9Cg==