Uva 10305 Solution

#include<bits/stdc++.h>
#define White 1
#define Gray 2
#define Black 3
#define N 10020
using namespace std;
int a[N][N], c[N], node, edge;
stack<int>st;

void dfsvisit(int x)
{
    c[x] = Gray;
    for(int i=1; i<=node; i++)
    {
        if(a[x][i] == 1)
        {
            if(c[i] == White)
                dfsvisit(i);
        }
    }

    c[x] = Black;
    st.push(x);
}

void dfs()
{
    for(int i=1; i<=node; i++)
        c[i] = White;

    for(int i=1; i<=node; i++)
    {
        if(c[i] == White)
            dfsvisit(i);
    }
}

int main()
{
    int n1, n2;
    while(cin >> node >> edge)
    {
        if(node == 0 && edge == 0)
            break;

        for(int i=1; i<=edge; i++)
        {
            cin >> n1 >> n2;
            a[n1][n2] = 1;
        }

        dfs();
        int t = st.size(), i = 1;
        while(!st.empty())
        {
            cout << st.top();
            if(i != t)
            {
                cout << " ";
                i++;
            }
            st.pop();
        }
        cout << "\n";
    }
    return 0;
}

Comments