Cod sursa(job #2090198)

Utilizator popabogdanPopa Bogdan Ioan popabogdan Data 17 decembrie 2017 18:41:36
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

#define Nmax 100005

using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

int N, M;
vector <int> G[Nmax], Gt[Nmax];
bool vis[Nmax];
vector <int> S;
vector < vector <int> > ans;
vector <int> c;

void DF(int node)
{
    vis[node] = true;
    for(auto it : G[node])
        if(!vis[it])
            DF(it);
    S.push_back(node);
}

void DFS(int node)
{
    c.push_back(node);
    vis[node] = true;
    for(auto it : Gt[node])
        if(!vis[it])
            DFS(it);
}

int main()
{
    fin >> N >> M;
    while(M--)
    {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        Gt[y].push_back(x);
    }
    for(int i = 1; i <= N; i++)
        if(!vis[i])
            DF(i);
    memset(vis, false, sizeof(vis));
    reverse(S.begin(), S.end());
    for(auto it : S)
        if(!vis[it])
        {
            c.clear();
            DFS(it);
            ans.push_back(c);
        }
    fout << ans.size() << "\n";
    for(auto V : ans)
    {
        sort(V.begin(), V.end());
        for(auto it : V)
            fout << it << " ";
        fout << "\n";
    }
    return 0;
}