Cod sursa(job #2176383)

Utilizator nicu_serteSerte Nicu nicu_serte Data 17 martie 2018 00:26:55
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
#define nmax 100005
int n, m, st[nmax], k, nr;
vector<int> g[nmax], gt[nmax], comp[nmax];
bool viz[nmax];
void citire()
{
    int i, x, y;
    fin>>n>>m;
    for(i=1; i<=m; i++)
    {
        fin>>x>>y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    fin.close();
}
void dfs(int nod)
{
    vector<int>::iterator it;
    viz[nod]=1;
    for(it=g[nod].begin(); it!=g[nod].end(); it++)
        if(!viz[*it])
            dfs(*it);
    st[++k]=nod;
}
void dfst(int nod)
{
    vector<int>::iterator it;
    viz[nod]=0;
    comp[nr].push_back(nod);
    for(it=gt[nod].begin(); it!=gt[nod].end(); it++)
        if(viz[*it])
            dfst(*it);
}
int main()
{
    int i;
    vector<int>::iterator it;
    citire();
    for(i=1; i<=n; i++)
        if(!viz[i])
            dfs(i);
    for(i=n; i>=1; i--)
        if(viz[st[i]])
        {
            nr++;
            dfst(st[i]);
        }
    fout<<nr<<'\n';
    for(i=1; i<=nr; i++)
    {
        for(it=comp[i].begin(); it!=comp[i].end(); it++)
            fout<<*it<<' ';
        fout<<'\n';
    }
    fout.close();
    return 0;
}