Cod sursa(job #3375026)

Utilizator RapiesNechifor Rares-Gabriel Rapies Data 9 noiembrie 2026 23:11:42
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

int n, m, cnt;
vector<vector<int>> G, GT, CTC;
vector<int> S;
vector<bool> v;

void DFS(int x)
{
    v[x] = 1;
    for (auto I = G[x].begin(); I != G[x].end(); I++)
        if (v[*I] == 0)
            DFS(*I);
    S.push_back(x);
}

void DFST(int x)
{
    v[x] = 1;
    CTC.back().push_back(x);
    for (auto I = GT[x].begin(); I != GT[x].end(); I++)
        if (v[*I] == 0)
            DFST(*I);
}

int main()
{
    fin >> n >> m;
    G = GT = vector<vector<int>>(n + 1);
    for (int k = 1; k <= m; ++k)
    {
        int i, j;
        fin >> i >> j;
        G[i].push_back(j);
        GT[j].push_back(i);
    }

    v = vector<bool>(n + 1, false);
    for (int i = 1; i <= n; ++i)
        if (v[i] == 0)
            DFS(i);

    v = vector<bool>(n + 1, false);
    for (auto I = S.rbegin(); I != S.rend(); I++)
        if (v[*I] == 0)
        {
            cnt++;
            CTC.push_back(vector<int>());
            DFST(*I);
        }

    fout << cnt << "\n";
    for (int i = 0; i < cnt; ++i)
    {
        for (int nod : CTC[i])
            fout << nod << " ";
        fout << "\n";
    }
    return 0;
}