Cod sursa(job #2725182)

Utilizator rares2004Ioan Rares rares2004 Data 18 martie 2021 15:26:29
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

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

const int N = 100005;

stack <int> stiva;
vector <int> a[N], a_t[N], ctc[N];

int viz[N], viz_t[N], nc = 0;


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

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

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


    return 0;
}