Cod sursa(job #1908515)

Utilizator justsomedudePalade Thomas-Emanuel justsomedude Data 7 martie 2017 09:07:52
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;
ifstream fin ("ctc.in");
ofstream fout ("ctc.out");

vector <int> L[100004], H[100004], S[100004];

int n, m, st[100004], cnt;
bool viz[100004];

void citire()
{
    fin >> n >> m;
    int x, y;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        H[y].push_back(x);
    }
}

void DFS1(int k)
{
    viz[k] = 1;
    for(int i = 0; i < L[k].size(); i++)
        if(!viz[L[k][i]])
            DFS1(L[k][i]);
    st[++st[0]] = k;
}

void DFS2(int k)
{
    viz[k] = 1;
    for(int i = 0; i < H[k].size(); i++)
        if(!viz[H[k][i]])
            DFS2(H[k][i]);
    S[cnt].push_back(k);
}

void solutie()
{
    for(int i = 1; i <= n; i++)
        if(!viz[i])
            DFS1(i);
    for(int i = 1; i <= n; i++)
        viz[i] = 0;
    while(st[0] > 0)
    {
        int nod = st[st[0]];
        if(!viz[nod])
        {
            DFS2(nod);
            cnt++;
        }
        st[0]--;
    }
}

int main()
{
    citire();
    solutie();
    fout << cnt << '\n';
    for(int i = 0; i <= cnt; i++, fout << '\n')
        for(int j = 0; j < S[i].size();fout << S[i][j] << " ", j++);
    return 0;
}