Cod sursa(job #2810997)

Utilizator stefanvoicaVoica Stefan stefanvoica Data 30 noiembrie 2021 20:38:29
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include<bits/stdc++.h>
#define dim 100002
#define mod 1000000007
//#define int long long
using namespace std;
ifstream fin ("ctc.in");
ofstream fout("ctc.out");
int n,nr;
vector<int> a[dim],t[dim],sol[dim];
stack<int> stk;
bool viz[dim];

void dfs (int nod)
{
    viz[nod]=1;
    for (int son:a[nod])
        if (!viz[son])
            dfs (son);
    stk.push(nod);
}

void dfs2 (int nod)
{
    sol[nr].push_back(nod);
    viz[nod]=1;
    for (int son:t[nod])
        if (!viz[son])
            dfs2(son);
}

void tare_conex ()
{
    while (!stk.empty())
    {
        int nod=stk.top();
        stk.pop();
        if (!viz[nod])
        {
            nr++;
            dfs2(nod);
        }
    }
}

void solve ()
{
    int m,x,y;
    fin>>n>>m;
    while (m--)
    {
        fin>>x>>y;
        a[x].push_back(y);
        t[y].push_back(x);
    }
    for (int i=1; i<=n; i++)
        if (!viz[i])
            dfs (i);
    for (int i=1; i<=n; i++)
        viz[i]=0;
    tare_conex();
    fout<<nr<<'\n';
    for (int i=1; i<=nr; i++)
    {
        for (int q:sol[i])
            fout<<q<<' ';
        fout<<'\n';
    }
}

int32_t main()
{
    int t=1;
    //cin>>t;
    //  cin.get();
    while(t--)
    {
        solve ();
        //   cout<<'\n';
    }
    return 0;
}