Cod sursa(job #2134236)

Utilizator flaviu_2001Craciun Ioan-Flaviu flaviu_2001 Data 17 februarie 2018 19:24:26
Problema Componente tare conexe Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <bits/stdc++.h>

using namespace std;

int n, m, p, post[100005], nrsol;
vector<int> v[100005], vt[100005], sol[100005];
bool ok[100005];

void df(int x)
{
    ok[x] = 1;
    for (vector<int>::iterator it = v[x].begin(); it != v[x].end(); ++it)
        if(!ok[*it]){
            ok[*it] = 1;
            df(*it);
        }
    post[++p] = x;
}

void dft(int x)
{
    sol[nrsol].push_back(x);
    ok[x] = 0;
    for (vector<int>::iterator it = vt[x].begin(); it != vt[x].end(); ++it)
        if(ok[*it]){
            ok[*it] = 0;
            dft(*it);
        }
}

int main()
{
    ifstream fin ("ctc.in");
    ofstream fout ("ctc.out");
    fin >> n >> m;
    while(m--){
        int x, y;
        fin >> x >> y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i)
        if(!ok[i])
            df(i);
    for (int i = p; i >= 1; --i)
        if(ok[post[i]]){
            ++nrsol;
            dft(post[i]);
        }
    fout << nrsol << "\n";
    for (int i = 1; i <= nrsol; ++i){
        for (vector<int>::iterator it = sol[i].begin(); it != sol[i].end(); ++it)
            fout << *it << " ";
        fout << "\n";
    }
    return 0;
}