Cod sursa(job #2842731)

Utilizator raduonofreiRadu Onofrei raduonofrei Data 1 februarie 2022 13:33:23
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#define NMAX 100002

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

int n, m;

vector <int> G[NMAX];
vector <int> GT[NMAX];
vector <int> ctc[NMAX];
bool viz[NMAX];
int nr, poz;
int postordine[NMAX];

void citire();
void afisare();
void DFS(int x);
void DFST(int x);

int main()
{
 citire();
 for (int i=1; i<=n; i++)
    if (!viz[i]) DFS(i);
 for (int i=n; i>0; i--) {
    if (viz[postordine[i]]==1) {
        nr++;
        DFST(postordine[i]);
    }
 }
 afisare();
 return 0;
}

void citire() {
    int x, y;
    fin>>n>>m;
    for (int i=1; i<=m; i++) {
        fin>>x>>y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}


void DFS(int x) {
    unsigned int i;
    viz[x] = 1;

    for(i=0; i<G[x].size(); i++)
        if (!viz[G[x][i]]) DFS(G[x][i]);
    postordine[++poz] = x;
}

void DFST(int x) {
    unsigned int i;
    viz[x] = 0;
    ctc[nr].push_back(x);
    for(i=0; i<GT[x].size(); i++)
        if (viz[GT[x][i]] == 1)
            DFST(GT[x][i]);
}

void afisare() {
    fout<<nr<<'\n';
    for (int i=1; i<=nr; i++) {
        for (int j=0; j<ctc[i].size(); j++) {
            fout<<ctc[i][j]<<' ';
        }
        fout<<'\n';
    }

}