Cod sursa(job #3211086)

Utilizator ana_valeriaAna Valeria Duguleanu ana_valeria Data 8 martie 2024 14:52:20
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <algorithm>
#include <vector>
#define MAX 50000
using namespace std;
ifstream cin ("ctc.in");
ofstream cout ("ctc.out");
int vis[MAX + 10], st[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] = 1;
    for (const auto &next : graphInv[node])
        if (vis[next] == 0)
            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++)
        vis[i] = 0;
    for (int i = 1; i <= n; i++)
        if (vis[st[i]] == 0)
        {
            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;
}