Cod sursa(job #2937378)

Utilizator crivoicarlaCrivoi Carla crivoicarla Data 10 noiembrie 2022 11:32:16
Problema Componente tare conexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
//
// Created by Carla on 20-Oct-22.
//

#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n,m,nr,x,y;
bool viz[100005];
vector <int> ls1[100005], ls2[100005], q, componente[100005];

void DFS1(int nod)
{
    viz[nod] = true;
    for(auto vecin : ls1[nod])
    {
        if(viz[vecin]==0) DFS1(vecin);
    }
    q.push_back(nod); //adaug in stiva nodurile parcurse
}


void DFS2(int nod)
{
    viz[nod] = true;
    componente[nr].push_back(nod); //creez componentele tari conexe
    for(auto vecin : ls2[nod])
    {
        if(viz[vecin]==0) DFS2(vecin);
    }
}

int main()
{
    fin>>n>>m;
    for(int i=1; i<=m; i++)
    {
        fin>>x>>y;
        ls1[x].push_back(y); //lista adj
        ls2[y].push_back(x); //lista adj
    }
    for(int i = 1; i <= n; i++)
        if(viz[i]==0) DFS1(i); //parcurg nodurile
        // retsratez
    for(int i = 1; i <= n; i++){
        viz[i] = 0;
    }

    for(int i = q.size() - 1; i >= 0; i--)
    {
        if(viz[q[i]]==0)
        {
            nr++;
            DFS2(q[i]);
        }
    }
    fout<<nr<<endl;
    for(int i = 1; i <= nr; i++)
    {
        for(int vecin : componente[i]){
            fout<<vecin<< ' ';
        }
        fout<<endl;
    }
    return 0;
}