#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stack>
using namespace std;
unordered_map<int, unordered_set<int>> g;
void addEdge(int x, int y) {
g[x].insert(y);
}
void topSort() {
unordered_set<int> visited;
stack<int> mainStack;
for(auto it = g.begin(); it != g.end(); it++) {
if(visited.count(it->first) == 0) {
visited.insert(it->first);
stack<int> locStack;
locStack.push(it->first);
while(!locStack.empty()) {
int curr = locStack.top();
bool unVisCh = false;
for(auto it2 = g[curr].begin(); it2 != g[curr].end(); it2++) {
int child = *it2;
if(visited.count(child) == 0) {
unVisCh = true;
visited.insert(child);
locStack.push(child);
}
}
if(!unVisCh) {
locStack.pop();
mainStack.push(curr);
}
}
}
}
while(!mainStack.empty()) {
cout<<mainStack.top()<<" ";
mainStack.pop();
}
cout<<endl;
}
int main() {
addEdge(1,2);
addEdge(4,5);
addEdge(5,6);
addEdge(3,2);
addEdge(2,6);
addEdge(1,3);
addEdge(4,3);
topSort();
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dW5vcmRlcmVkX21hcD4KI2luY2x1ZGUgPHVub3JkZXJlZF9zZXQ+CiNpbmNsdWRlIDx2ZWN0b3I+CiNpbmNsdWRlIDxzdGFjaz4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnVub3JkZXJlZF9tYXA8aW50LCB1bm9yZGVyZWRfc2V0PGludD4+IGc7Cgp2b2lkIGFkZEVkZ2UoaW50IHgsIGludCB5KSB7CglnW3hdLmluc2VydCh5KTsKfQoKdm9pZCB0b3BTb3J0KCkgewoJdW5vcmRlcmVkX3NldDxpbnQ+IHZpc2l0ZWQ7CglzdGFjazxpbnQ+IG1haW5TdGFjazsKCQoJZm9yKGF1dG8gaXQgPSBnLmJlZ2luKCk7IGl0ICE9IGcuZW5kKCk7IGl0KyspIHsKCQlpZih2aXNpdGVkLmNvdW50KGl0LT5maXJzdCkgPT0gMCkgewoJCQl2aXNpdGVkLmluc2VydChpdC0+Zmlyc3QpOw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