Cod sursa(job #3002749)

Utilizator brianna_enacheEnache Brianna brianna_enache Data 15 martie 2023 08:28:14
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, st[100005], top, nr_comp;
vector<int> a[100005], b[100005], cmp[100005];
bitset<100005> viz;

void DFS(int x)
{
    viz[x] = 1;
    for (int e : a[x])
        if (viz[e] == 0) DFS(e);
    st[++top] = x;
}

void DFS1(int x)
{
    viz[x] = 1;
    for (int e : b[x])
        if (viz[e] == 0) DFS1(e);
    cmp[nr_comp].push_back(x);
}

int main()
{
    int x, y;
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        a[x].push_back(y);
        b[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (viz[i] == 0)
            DFS(i);
    viz.reset();
    for (int i = n; i >= 1; i--)
        if (viz[st[i]] == 0)
        {
            nr_comp++;
            DFS1(st[i]);
        }
        fout << nr_comp << "\n";
    for (int i = 1; i <= nr_comp; i++)
    {
        sort(cmp[i].begin(), cmp[i].end());
        for (int e : cmp[i])
            fout << e << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}