Cod sursa(job #3214235)

Utilizator ana_valeriaAna Valeria Duguleanu ana_valeria Data 13 martie 2024 22:02:20
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <algorithm>
#include <vector>
#define MAX 100000
using namespace std;
ifstream cin ("ctc.in");
ofstream cout ("ctc.out");
int st[MAX + 10], vis[MAX + 10], cnt, cntComp;
vector <int> graph[MAX + 10], graphInv[MAX + 10], comp[MAX + 10];
void dfs(int node)
{
    vis[node] = 1;
    for (const auto &next : graph[node])
        if (vis[next] == 0)
            dfs(next);
    cnt++;
    st[cnt] = node;
}
void dfsCTC(int node)
{
    vis[node] = 2;
    for (const auto &next : graphInv[node])
        if (vis[next] == 1)
            dfsCTC(next);
    comp[cntComp].push_back(node);
}
int main()
{
    int n, m;
    cin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        cin >> x >> y;
        graph[x].push_back(y);
        graphInv[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (vis[i] == 0)
            dfs(i);
    reverse(st + 1, st + n + 1);
    for (int i = 1; i <= n; i++)
        if (vis[st[i]] == 1)
        {
            cntComp++;
            dfsCTC(st[i]);
        }
    cout << cntComp << '\n';
    for (int i = 1; i <= cntComp; i++)
    {
        for (const auto &it : comp[i])
            cout << it << ' ' ;
        cout << '\n';
    }
    return 0;
}