Cod sursa(job #2702315)

Utilizator DragosC1Dragos DragosC1 Data 3 februarie 2021 17:41:43
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;

vector<int> a[100001], at[100001];
bool viz[100001];
int post_ordine[100001], l;

vector<int> cc[100001]; int nrc;

int n;

void dfs(int x) {
    int i;
    viz[x] = 1;
    for (i = 0; i < a[x].size(); i++)
        if (!viz[a[x][i]])
            dfs(a[x][i]);
    post_ordine[++l] = x;
}

void dfsT(int x) {
    int i;
    viz[x] = 0;
    cc[nrc].push_back(x);
    for (i = 0; i < at[x].size(); i++)
        if (viz[at[x][i]])
            dfsT(at[x][i]);
}


int main() {
    int i, m, x, y, j;

    ifstream f("ctc.in");
    f >> n >> m;
    for (i = 1; i <= m; i++) {
        f >> x >> y;
        a[x].push_back(y);
        at[y].push_back(x);
    }
    f.close();

    for (i = 1; i <= n; i++)
        if (!viz[i])
            dfs(i);

    for (i = l; i >= 1; i--) 
        if (viz[post_ordine[i]]) {
            nrc++;
            dfsT(post_ordine[i]);
        }

    ofstream g("ctc.out");
    g << nrc << '\n';
    for (i = 1; i <= nrc; i++, g << '\n')  {
        sort(cc[i].begin(), cc[i].end());
        for (j = 0; j < cc[i].size(); j++)
            g << cc[i][j] << ' ';
    }
    g.close();

    return 0;
}