Cod sursa(job #3213295)

Utilizator QwertyDvorakQwerty Dvorak QwertyDvorak Data 12 martie 2024 20:55:59
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;

#define pb push_back
#define mp make_pair
#define dbg(x) cout << #x << ": " << x << "\n";
using ll = long long;

const string myf = "ctc";
ifstream fin(myf + ".in");
ofstream fout(myf + ".out");

int n, m;
int nrc;
vector<int> g[100005], rg[100005];
vector<int> pops;
bitset<100005> viz;
vector<int> ans[100005];
void dfs(int nod)
{
    viz[nod] = 1;
    for (auto i : g[nod])
        if (!viz[i])
            dfs(i);
    pops.pb(nod);
}

void dfsr(int nod)
{
    viz[nod] = 1;
    ans[nrc - 1].pb(nod);
    for (auto i : rg[nod])
        if (!viz[i])
            dfsr(i);
}

int main()
{
    int x, y;
    fin >> n >> m;
    while (m--)
    {
        fin >> x >> y;
        g[x].pb(y);
        rg[y].pb(x);
    }
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            dfs(i);
    viz.reset();

    for (int i = n - 1; i >= 0; --i)
        if (!viz[pops[i]])
        {
            nrc++;
            dfsr(pops[i]);
        }
    fout << nrc << '\n';

    for (int i = 0; i < nrc; i++)
        sort(ans[i].begin(), ans[i].end());
    for (int i = 0; i < nrc; i++)
    {
        for (auto j : ans[i])
            fout << j << " ";
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}