Cod sursa(job #1360001)

Utilizator PetrutiuPaulPetrutiu Paul Gabriel PetrutiuPaul Data 25 februarie 2015 10:43:20
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

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

vector <int> G[1000000];
vector <int> Gi[1000000];
vector <int> Go[1000000];
vector <int> used;
vector <int> discovered;
vector <int> where;

void DFP(const int n, vector <int> *G)
{
    vector<int>::iterator it;
    used[n]=true;

    for(it=G[n].begin();it!=G[n].end();it++)
        if(used[*it]==false)
            DFP(*it,G);
    discovered.push_back(n);
}

void DFM(const int n, vector <int> *G, const int which)
{
    vector<int>::iterator it;
    where[n]=which;

    for(it=G[n].begin();it!=G[n].end();it++)
        if(where[*it]==-1)
            DFM(*it,G,which);
}


int main()
{
    int i,j,n,m,x,y;
    fin>>n>>m;
    for(i=1;i<=m;i++)
    {
        fin>>x>>y;
        Go[x-1].push_back(y-1);
        Gi[y-1].push_back(x-1);
    }

    used.resize(n);
    used.assign(used.size(),0);
    where.assign(where.size(),-1);

    for(i=0;i<n;i++)
        if(used[i]==false)
            DFP(i,Go);

    where.resize(n);
    where.assign(where.size(),-1);

    int coun=0;

    for(;discovered.size();discovered.pop_back())
    {
        if(where[discovered.back()]==-1)
            {
                DFM(discovered.back(),Gi,coun);
                coun++;
            }
    }

    for(i=0;i<n;i++)
        G[where[i]].push_back(i);


    vector<int>::const_iterator it;

    fout<<coun<<'\n';

    for(i=0;i<coun;++i)
        {
            for(it=G[i].begin();it!=G[i].end();it++)
                fout<<*it+1<<' ';
        fout<<'\n';
        }

}