UVa : 11709 (Trust groups)



// http://uva.onlinejudge.org/external/117/11709.html
// Runtime: 1.384
// Tag: Strongly Connected Components (SCC)

/* 
 * File:   main.cpp
 * Author: shahab
 * Created on April 15, 2011, 2:07 AM
 */

// @BEGIN_OF_SOURCE_CODE

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <list>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <bitset>
#include <utility>
#include <set>
#include <numeric>

#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define pi acos(-1.0)
#define N  1010
#define LL long long

#define For(i, a, b) for( int i = (a); i < (b); i++ )
#define Fors(i, sz) for( size_t i = 0; i < sz.size (); i++ )
#define Fore(it, x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++)
#define Set(a, s) memset(a, s, sizeof (a))
#define Read(r) freopen(r, "r", stdin)
#define Write(w) freopen(w, "w", stdout)

using namespace std;

vector <int> edges [N];
vector <int> rEdges [N];
bool vis [N];
vector <int> sortedNode;

void reset ()
{
    For (i, 0, N) {
        edges [i].clear();
        rEdges [i].clear();
    }

    sortedNode.clear();
    Set (vis, false);
}

void dfs1 (int x)
{
    vis [x] = true;

    Fors (u, edges [x])
        if ( !vis [edges [x] [u]] ) dfs1 (edges [x] [u]);

    sortedNode.push_back(x);
}

void dfs2 (int x)
{
    vis [x] = false;

    Fors (u, rEdges [x])
        if ( vis [rEdges [x] [u]] ) dfs2 (rEdges [x] [u]);
}

int main(int argc, char** argv)
{
    //Read ("in");
    //Write ("out");
    int p, t;

    while ( scanf ("%d %d", &p, &t) ) {
        if ( p == 0 && t == 0 ) break;
        getchar ();

        reset ();
        char name [100];
        map <string, int> name_index;

        For (i, 1, p + 1) {
            gets (name);
            name_index [name] = i;
        }

        char name1 [100];
        char name2 [100];

        For (i, 0, t) {
            gets (name1);
            gets (name2);
            edges [name_index [name1]].push_back(name_index [name2]);
            rEdges [name_index [name2]].push_back(name_index [name1]);
        }

        For (i, 1, p + 1) 
            if ( !vis [i] ) dfs1 (i);

        int c = 0;

        for ( int i = sortedNode.size() - 1; i >= 0; i-- ) {
            if ( vis [sortedNode [i]] ) {
                dfs2 (sortedNode [i]); c++;
            }
        }

        printf ("%d\n", c);

    }

    return 0;
}

// @END_OF_SOURCE_CODE
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s