Cod sursa(job #375196)

Utilizator alexandru92alexandru alexandru92 Data 19 decembrie 2009 19:48:54
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
/* 
 * File:   main.cpp
 * Author: virtualdemon
 *
 * Created on December 19, 2009, 7:28 PM
 */
#include <stack>
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>
#define pb push_back

/*
 * 
 */
using namespace std;
vector<int> c, df, uz;
vector< vector<int> > v, vt, tc;
void DFS( int x )
{stack<int> s;
 vector<int>::const_iterator it, iend;
    uz[x]=1;
    s.push(x);
    while( !s.empty() )
    {
        x=s.top(); s.pop();
        df.pb(x);
        for( it=v[x].begin(), iend=v[x].end(); it < iend; ++it )
            if( !uz[*it] )
            {
                uz[*it]=1;
                s.push(*it);
            }
    }
}
void DFST( int x )
{stack<int> s;
 vector<int>::const_iterator it, iend;
    uz[x]=2;
    s.push(x);
    while( !s.empty() )
    {
        x=s.top(); s.pop();
        c.pb(x+1);
        for( it=vt[x].begin(), iend=vt[x].end(); it < iend; ++it )
            if( 1 == uz[*it] )
            {
                uz[*it]=2;
                s.push(*it);
            }
    }
}
int main()
{int n, m, x, y, i, count=0;
    ifstream in("ctc.in");
    in>>n>>m;
    v.resize(n);
    vt.resize(n);
    uz.resize(n);
    while( m-- )
    {
        in>>x>>y;
        v[x-1].pb(y-1);
        vt[y-1].pb(x-1);
    }
    for( i=0; i < n; ++i )
        if( 0 == uz[i] )
            DFS(i);
    for( i=0; i < n; ++i )
        if( 1 == uz[df[i]] )
        {c.clear();
            DFST(df[i]);
            ++count;
            tc.resize(count);
            copy( c.begin(), c.end(), back_inserter(tc[count-1]) );
        }
    ofstream out("ctc.out");
    out<<count<<'\n';
    for( i=0; i < count; ++i )
    {
        copy( tc[i].begin(), tc[i].end(), ostream_iterator<int>(out, " ") );
        out<<'\n';
    }
    return 0;
}