Cod sursa(job #2727999)

Utilizator rarestudurTudur Rares rarestudur Data 22 martie 2021 18:10:16
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>
using namespace std;

const int N = 100001;
int n,nc;

vector <int> a[N],a_t[N],ctc[N];
bitset <N> viz;
stack <int> s;

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

void dfs(int x)
{
    viz[x] = 1;
    for(auto y:a[x])
    {
        if(!viz[y])
        {
            dfs(y);
        }
    }
    s.push(x);
}

void dfs_t(int x)
{
    viz[x] = 1;
    ctc[nc].push_back(x);
    for(auto y : a_t[x])
    {
        if (!viz[y])
        {
            dfs_t(y);
        }
    }
}

int main()
{
    int m;
    in >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int x,y;
        in >> x >> y;
        a[x].push_back(y);
        a_t[y].push_back(x);
    }
    in.close();
    for(int i = 1; i <= n; i++)
    {
        if(!viz[i])
        {
            dfs(i);
        }
    }
    viz.reset();
    while(!s.empty())
    {
        int x = s.top();
        s.pop();
        if(!viz[x])
        {
            nc++;
            dfs_t(x);
        }
    }
    out << nc << "\n";
    for(int i = 1; i <= nc; i++)
    {
        for(auto x: ctc[i])
        {
            out << x << " ";
        }
        out << "\n";
    }
    out.close();
    return 0;
}