UVa 10305 - Ordering Tasks

/****************************
*                           *
*   @Author: Pranta Sarker  *
*    @Status: Accepted       *
*                           *
****************************/


#include<bits/stdc++.h>
using namespace std;

#define sf scanf
#define pf printf
#define psb push_back

const int high=205;
const int white=0;
const int grey=1;
const int black=-1;

vector<int>adj[high];
int status[high];
vector<int>sortedList;

void CLR()
{
    int i=0;

    for(i=0; i<high; i++)
    {
        status[i]=white;
        adj[i].clear();
    }

    sortedList.clear();
}

void Topo_Sort(int u)
{
    status[u] = grey;

    int i, sze = adj[u].size();

    for(i=0; i<sze; i++)
    {
        int v = adj[u][i];

        if(status[v] == white)
        {
            Topo_Sort(v);
        }
    }

    status[u] = black;
    sortedList.push_back(u);
}

int main()
{
    int u, v, i, n, m;

    while(sf("%d %d", &n, &m)==2)
    {
        if(!m && !n) break;

        CLR();

        for(i=0; i<m; i++)
        {
            sf("%d %d", &u, &v);

            adj[u].psb(v);
        }

        for(i=1; i<=n; i++)
        {
            if(status[i]==white)
            {
                Topo_Sort(i);
            }
        }

        reverse(sortedList.begin(), sortedList.end());

        int sze = sortedList.size();

        pf("%d", sortedList[0]);

        for(i=1; i<sze; i++)
        {
            pf(" %d", sortedList[i]);
        }

        pf("\n");
    }

    return 0;
}


/*


5 4
1 2
2 3
1 3
1 5

*/

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number