Cod sursa(job #375207)

Utilizator alexandru92alexandru alexandru92 Data 19 decembrie 2009 20:14:07
Problema Componente tare conexe Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 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;
inline void DFS( int x )
{vector<int>::const_iterator it=v[x].begin(), iend=v[x].end();
    uz[x]=1;
    for( ; it < iend; ++it )
        if( !uz[*it] )
            DFS(*it);
   df.pb(x);
}
void DFST( int x )
{stack<int> s;
 vector<int>::const_iterator it, iend;
    uz[x]=0;
    for( s.push(x); !s.empty(); x=s.top(), s.pop() )
    {c.pb(x+1);
        for( it=vt[x].begin(), iend=vt[x].end(); it < iend; ++it )
            if( uz[*it] )
            {
                uz[*it]=0;
                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( !uz[i] )
            DFS(i);
    for( i=n-1; i >= 0; --i )
        if( 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;
}