UVa 11504 - Dominos

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

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

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

const int white = 0;
const int grey = 1;
const int black = -1;
const int high = (2e5)+10;

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

void CLR()
{
    for(int i=0; i<high; i++)
    {
        adj[i].clear();
    }

    sortedList.clear();
}

void CLR_status()
{
    for(int i=0; i<high; i++)
    {
        status[i] = white;
    }
}

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

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

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

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

    if(pmeter == 0)
    {
        sortedList.push_back(u);
    }

    status[u] = black;
}

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

    sf("%d", &test);

    while(test--)
    {
        CLR();
        CLR_status();

        sf("%d %d", &n , &m);

        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, 0);
            }
        }

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

        CLR_status();

        int cnt = 0;

        int sze = sortedList.size();

        //for(i=0; i<sze; i++) cout << sortedList[i] << "; ";

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

            if(status[v] == white)
            {
                cnt+=1;

                Topo_Sort(v, 1);
            }
        }

        pf("%d\n", cnt);
    }

    return 0;
}

Comments

Popular posts from this blog

SPOJ-CMG - Collecting Mango

LightOJ 1009 - Back to Underworld

LeetCode Palindrome Number