Topological Algorithm Source Code (C/C++)



// @BEGIN_OF_SOURCE_CODE

#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
using namespace std;

int main ()
{
    vector <int> matrix [100];

    for ( int i = 0; i < edges; i++ ) {
        matrix [a].push_back (b);
        inDegree [b]++;
    }

    queue <int> Q;

    for ( int i = 1; i <= vertex; i++ ) {
        if ( inDegree [i] == 0 )
            Q.push (i);
    }

    vector <int> sortedList;

    while ( !Q.empty () ) {
        int pop = Q.front ();
        Q.pop ();

        sortedList.push_back (pop);

        for ( int i = 0; i < matrix [pop].size (); i++ ) {
            inDegree [matrix [pop] [i]]--;
            if ( inDegree [matrix [pop] [i]] == 0 )
                Q.push (matrix [pop] [i]);
        }
    }

    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