Cod sursa(job #2119697)

Utilizator AndreiTurcasTurcas Andrei AndreiTurcas Data 1 februarie 2018 15:55:21
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#define in vector<int> :: iterator
#define lim 200005
using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

int n, m, trans[lim], nrc, t;
vector<int> G[lim], tG[lim], scc[lim];
bitset<lim> B;

inline void Dfs(int node)
{
    B[node] = 1;
    for(in it = G[node].begin(); it != G[node].end(); ++it)
        if(!B[*it])
            Dfs(*it);
    trans[++t] = node;
}

inline void Dfs_t(int node)
{
    B[node] = 0;
    scc[nrc].push_back(node);
    for(in it = tG[node].begin(); it != tG[node].end(); ++it)
        if(B[*it])
            Dfs_t(*it);
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x, y;
        f >> x >> y;
        G[x].push_back(y);
        tG[y].push_back(x);
    }
    for(int i = 1; i <= n; ++i)
        if(!B[i])
            Dfs(i);
    for(int i = n; i >= 1; --i)
        if(B[trans[i]])
    {
            ++nrc;
            Dfs_t(trans[i]);
    }
    g << nrc << "\n";
    for(int i = 1; i <= nrc; ++i)
    {
        for(in it = scc[i].begin(); it != scc[i].end(); ++it)
            g << *it << " ";
        g << "\n";
    }
}