Cod sursa(job #2304457)

Utilizator HumikoPostu Alexandru Humiko Data 18 decembrie 2018 08:08:16
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("ctc.in");
ofstream fout ("ctc.out");

int n, m;
int f[100005];
vector <int> graph[100005];
vector <int> reversed_Graph[100005];
vector <int> solutions [100005];

stack <int> nodes;

void resetFrequency ()
{
    for ( int i = 1; i <= n+4; ++i )
        f[i] = 0;
}
void dfs(int source)
{
    f[source] = 1;

    for ( auto x:graph[source] )
        if ( !f[x] )
            dfs(x);

    nodes.push(source);
}

void reverseDfs(int source, int cnt)
{
    f[source] = 1;

    for ( auto x:reversed_Graph[source] )
        if ( !f[x] )
            reverseDfs(x, cnt);

    solutions[cnt].push_back(source);
}

int main()
{
    ios::sync_with_stdio(false);
    fin.tie(0); fout.tie(0);

    fin>>n>>m;
    for ( int i = 1; i <= m; ++i )
    {
        int a, b;
        fin>>a>>b;
        graph[a].push_back(b);
        reversed_Graph[b].push_back(a);
    }

    for ( int i = 1; i <= n; ++i )
        if ( !f[i] )
            dfs(i);

    resetFrequency();

    int cnt = 0;

    while ( nodes.size() )
    {
        if ( !f[nodes.top()] )
            reverseDfs(nodes.top(), ++cnt);
        nodes.pop();
    }

    fout<<cnt<<'\n';

    for ( int i = 1; i <= cnt; ++i )
    {
        for ( auto x:solutions[i] )
            fout<<x<<" ";
        fout<<'\n';
    }
}