//
// main.cpp
// Topological Sort
//
// Created by Himanshu on 10/09/21.
//
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void printStack (stack<int> st) {
while(!st.empty()) {
cout<<st.top()<<" ";
st.pop();
}
cout<<endl;
}
//n = number of nodes in graph
void topologicalSort (int x, int n, vector<int> graph[], int vis[], stack<int> &st) {
vis[x] = 1;
for (int i=0; i<graph[x].size(); i++) {
int j = graph[x][i];
if (vis[j] == 0) {
topologicalSort(j, n, graph, vis, st);
}
}
st.push(x);
}
int main() {
int s = 1, n = 6;
vector<int> graph[n+1];
int vis[n+1];
stack<int> st;
graph[1].push_back(2);
graph[2].push_back(3);
graph[2].push_back(4);
graph[3].push_back(4);
graph[4].push_back(6);
graph[4].push_back(5);
for (int i=1; i<=n; i++) {
vis[i] = 0;
}
cout<<"Graph:"<<endl;
for (int i=1; i<=n; i++) {
if (graph[i].size() > 0) {
cout<<i<<": ";
}
for (int j=0; j<graph[i].size(); j++) {
cout<<graph[i][j]<<" ";
}
if (graph[i].size() > 0) {
cout<<endl;
}
}
cout<<endl<<"Topological Sort:"<<endl;
topologicalSort(s, n, graph, vis, st);
printStack(st);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBUb3BvbG9naWNhbCBTb3J0Ci8vCi8vICBDcmVhdGVkIGJ5IEhpbWFuc2h1IG9uIDEwLzA5LzIxLgovLwoKI2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8c3RhY2s+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgp2b2lkIHByaW50U3RhY2sgKHN0YWNrPGludD4gc3QpIHsKICAgIHdoaWxlKCFzdC5lbXB0eSgpKSB7CiAgICAgICAgY291dDw8c3QudG9wKCk8PCIgIjsKICAgICAgICBzdC5wb3AoKTsKICAgIH0KICAgIGNvdXQ8PGVuZGw7Cn0KCgovL24gPSBudW1iZXIgb2Ygbm9kZXMgaW4gZ3JhcGgKdm9pZCB0b3BvbG9naWNhbFNvcnQgKGludCB4LCBpbnQgbiwgdmVjdG9yPGludD4gZ3JhcGhbXSwgaW50IHZpc1tdLCBzdGFjazxpbnQ+ICZzdCkgewogICAgdmlzW3hdID0gMTsKICAgIGZvciAoaW50IGk9MDsgaTxncmFwaFt4XS5zaXplKCk7IGkrKykgewogICAgICAgIGludCBqID0gZ3JhcGhbeF1baV07CiAgICAgICAgaWYgKHZpc1tqXSA9PSAwKSB7CiAgICAgICAgICAgIHRvcG9sb2dpY2FsU29ydChqLCBuLCBncmFwaCwgdmlzLCBzdCk7CiAgICAgICAgfQogICAgfQogICAgc3QucHVzaCh4KTsKfQoKCmludCBtYWluKCkgewogICAgaW50IHMgPSAxLCBuID0gNjsKICAgIHZlY3RvcjxpbnQ+IGdyYXBoW24rMV07CiAgICBpbnQgdmlzW24rMV07CiAgICBzdGFjazxpbnQ+IHN0OwogICAgCiAgICBncmFwaFsxXS5wdXNoX2JhY2soMik7CiAgICBncmFwaFsyXS5wdXNoX2JhY2soMyk7CiAgICBncmFwaFsyXS5wdXNoX2JhY2soNCk7CiAgICBncmFwaFszXS5wdXNoX2JhY2soNCk7CiAgICBncmFwaFs0XS5wdXNoX2JhY2soNik7CiAgICBncmFwaFs0XS5wdXNoX2JhY2soNSk7CgogICAgCiAgICBmb3IgKGludCBpPTE7IGk8PW47IGkrKykgewogICAgICAgIHZpc1tpXSA9IDA7CiAgICB9CiAgICAKICAgIGNvdXQ8PCJHcmFwaDoiPDxlbmRsOwogICAgZm9yIChpbnQgaT0xOyBpPD1uOyBpKyspIHsKICAgICAgICBpZiAoZ3JhcGhbaV0uc2l6ZSgpID4gMCkgewogICAgICAgICAgICBjb3V0PDxpPDwiOiAiOwogICAgICAgIH0KICAgICAgICBmb3IgKGludCBqPTA7IGo8Z3JhcGhbaV0uc2l6ZSgpOyBqKyspIHsKICAgICAgICAgICAgY291dDw8Z3JhcGhbaV1bal08PCIgIjsKICAgICAgICB9CiAgICAgICAgaWYgKGdyYXBoW2ldLnNpemUoKSA+IDApIHsKICAgICAgICAgICAgY291dDw8ZW5kbDsKICAgICAgICB9CiAgICB9CiAgICAKICAgIGNvdXQ8PGVuZGw8PCJUb3BvbG9naWNhbCBTb3J0OiI8PGVuZGw7CiAgICB0b3BvbG9naWNhbFNvcnQocywgbiwgZ3JhcGgsIHZpcywgc3QpOwogICAgcHJpbnRTdGFjayhzdCk7CiAgICByZXR1cm4gMDsKfQo=