Timus 1022 Genealogical Tree Solution

#include <iostream>
#include <vector>
#include <bitset>
#include <algorithm>
#include <stack>
using namespace std;
vector<vector<int> > a(101);
bitset<101> vis;
stack<int> s;
void topo(int u){
    vis[u]=1;
    for(int i=0;i<a[u].size();i++)
        if(!vis[a[u][i]])
            topo(a[u][i]);
    s.push(u);
}
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n;i++){
        int x;
        cin>>x;
        while(x){
            a[i].push_back(x);
            cin>>x;
        }
    }
    for(int i=1;i<=n;i++)
        if(!vis[i])
            topo(i);
    cout<<s.top();
    s.pop();
    while(!s.empty()){
        cout<<' '<<s.top();
        s.pop();
    }
    cout<<endl;
}

Comments