Cod sursa(job #2536645)

Utilizator IulianOleniucIulian Oleniuc IulianOleniuc Data 2 februarie 2020 13:38:18
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <vector>
#include <fstream>

#define NMAX 100010
using std::vector;

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

int n, m;
bool vis[NMAX];

vector<int> ad1[NMAX];
vector<int> ad2[NMAX];

int nrComp;
vector<int> comp[NMAX];

int top;
int st[NMAX];

void dfs1(int node) {
    vis[node] = true;
    for (int i = 0; i < (int) ad1[node].size(); i++)
        if (!vis[ad1[node][i]])
            dfs1(ad1[node][i]);
    st[++top] = node;
}

void dfs2(int node) {
    vis[node] = true;
    comp[nrComp].push_back(node);

    for (int i = 0; i < (int) ad2[node].size(); i++)
        if (!vis[ad2[node][i]])
            dfs2(ad2[node][i]);
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        fin >> x >> y;

        ad1[x].push_back(y);
        ad2[y].push_back(x);
    }

    for (int i = 1; i <= n; i++)
        if (!vis[i])
            dfs1(i);

    for (int i = 1; i <= n; i++)
        vis[i] = false;

    while (top) {
        if (!vis[st[top]]) {
            dfs2(st[top]);
            nrComp++;
        }
        top--;
    }

    fout << nrComp << '\n';
    for (int i = 0; i < nrComp; i++) {
        for (int j = 0; j < (int) comp[i].size(); j++)
            fout << comp[i][j] << ' ';
        fout << '\n';
    }

    fout.close();
    return 0;
}