#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
int main() {
stack<pair<bool,int> > dfs;
stack<int> postOrder;
vector<int> newVec;
vector<int>::iterator it;
vector<vector<int> > graph {
{1, 2}
, {2, 3}
, {3, 4, 7}
, {4}
, {5}
, {6, 7}
, {}
, {6}
};
vector<bool> visited(graph.size());
for(int i=0;i<graph.size();i++){
if(visited[i]==false){
dfs.push(make_pair(false,i));
}
while(!dfs.empty()){
pair<bool,int> node=dfs.top();
dfs.pop();
if (node.first) {
postOrder.push(node.second);
cout << node.second << endl;
continue;
}
visited[node.second]=true;
dfs.push(make_pair(true, node.second));
newVec=graph[node.second]; //vector of neighboors
for(it=newVec.begin();it!=newVec.end();it++){
int son=*it;
if(visited[son]==false){
dfs.push(make_pair(false, son));
}
}
}
}
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8c3RhY2s+CiNpbmNsdWRlIDxhbGdvcml0aG0+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CgppbnQgbWFpbigpIHsKICAgIHN0YWNrPHBhaXI8Ym9vbCxpbnQ+ID4gZGZzOwogICAgc3RhY2s8aW50PiBwb3N0T3JkZXI7CiAgICB2ZWN0b3I8aW50PiBuZXdWZWM7CiAgICB2ZWN0b3I8aW50Pjo6aXRlcmF0b3IgaXQ7CiAgICB2ZWN0b3I8dmVjdG9yPGludD4gPiBncmFwaCB7CiAgICAJezEsIDJ9CiAgICAsICAgezIsIDN9CiAgICAsICAgezMsIDQsIDd9CiAgICAsICAgezR9CiAgICAsICAgezV9CiAgICAsICAgezYsIDd9CiAgICAsICAge30KICAgICwgICB7Nn0KICAgIH07CiAgICB2ZWN0b3I8Ym9vbD4gdmlzaXRlZChncmFwaC5zaXplKCkpOwoJZm9yKGludCBpPTA7aTxncmFwaC5zaXplKCk7aSsrKXsKICAgICAgICBpZih2aXNpdGVkW2ldPT1mYWxzZSl7CiAgICAgICAgICAgIGRmcy5wdXNoKG1ha2VfcGFpcihmYWxzZSxpKSk7CiAgICAgICAgfSAgIAogICAgICAgIHdoaWxlKCFkZnMuZW1wdHkoKSl7CiAgICAgICAgICAgIHBhaXI8Ym9vbCxpbnQ+IG5vZGU9ZGZzLnRvcCgpOwogICAgICAgICAgICBkZnMucG9wKCk7CiAgICAgICAgICAgIGlmIChub2RlLmZpcnN0KSB7CiAgICAgICAgICAgIAlwb3N0T3JkZXIucHVzaChub2RlLnNlY29uZCk7CiAgICAgICAgICAgIAljb3V0IDw8IG5vZGUuc2Vjb25kIDw8IGVuZGw7CiAgICAgICAgICAgIAljb250aW51ZTsKICAgICAgICAgICAgfQogICAgICAgICAgICB2aXNpdGVkW25vZGUuc2Vjb25kXT10cnVlOwogICAgICAgICAgICBkZnMucHVzaChtYWtlX3BhaXIodHJ1ZSwgbm9kZS5zZWNvbmQpKTsKICAgICAgICAgICAgbmV3VmVjPWdyYXBoW25vZGUuc2Vjb25kXTsgLy92ZWN0b3Igb2YgbmVpZ2hib29ycwogICAgICAgICAgICBmb3IoaXQ9bmV3VmVjLmJlZ2luKCk7aXQhPW5ld1ZlYy5lbmQoKTtpdCsrKXsKICAgICAgICAgICAgICAgIGludCBzb249Kml0OwogICAgICAgICAgICAgICAgaWYodmlzaXRlZFtzb25dPT1mYWxzZSl7CiAgICAgICAgICAgICAgICAgICAgZGZzLnB1c2gobWFrZV9wYWlyKGZhbHNlLCBzb24pKTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgfQogICAgICAgIH0KICAgIH0KCXJldHVybiAwOwp9