Cod sursa(job #2868471)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 10 martie 2022 22:38:17
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>
#define P 1999999973
using namespace std;

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

int viz[100005], n, m, s, st[100005], k, nrc;
vector<int>L[100005];
vector<int>R[100005];
vector<int>ctc[100005];

void Dfs(int nod)
{
    viz[nod] = 1;
    for(auto i : L[nod])
        if(!viz[i])
            Dfs(i);
    st[++k] = nod;
}

void Dfs2(int nod)
{
    viz[nod] = 0;
    for(auto i : R[nod])
        if(viz[i])
            Dfs2(i);
    ctc[nrc].push_back(nod);
}

void SCC()
{
    for(int i = 1; i <= n; i++)
        if(!viz[i])
            Dfs(i);
    for(int i = n; i >= 1; i--)
        if(viz[st[i]])
    {
        nrc++;
        Dfs2(st[i]);
    }
    fout << nrc << "\n";
    for(int i = 1; i <= nrc; i++, fout << "\n")
        for(auto j : ctc[i])
            fout << j << " ";
}

int main()
{
    int x, y, nrc = 0;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        R[y].push_back(x);
    }
    SCC();
    return 0;
}