Cod sursa(job #1496218)

Utilizator adina0822Ciubotaru Adina-Maria adina0822 Data 4 octombrie 2015 16:40:51
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
using namespace std;
#include <fstream>
#include <vector>
#define MAXN 100005
FILE *f=fopen("ctc.in", "r");
FILE *g=fopen("ctc.out","w");

vector<int> Go[MAXN],Gi[MAXN],G[MAXN];
vector<int> discovered, used, where;
int count=0,n;

void read()
{
    int m,x,y;
    fscanf(f,"%d%d",&n,&m);
    while(m--)
    {
        fscanf(f,"%d%d",&x,&y);
        Go[x-1].push_back(y-1);
        Gi[y-1].push_back(x-1);
    }
}

void DFP(int n)
{
    vector<int> :: iterator it;
    used[n]=1;
    for(it=Go[n].begin();it!=Go[n].end();it++)
      if(!used[*it])
        DFP(*it);
    discovered.push_back(n);
}

void DFM(int n, int which)
{
    vector<int>::iterator it;
    where[n]=which;
    for(it=Gi[n].begin(); it!=Gi[n].end(); it++)
      if(where[*it]==-1)
        DFM(*it,which);
}


void print()
{
    vector<int>::iterator it;

   fprintf(g,"%d\n",count);
   for(int i=0; i<count; i++)
     {
       for(it=G[i].begin(); it!=G[i].end();it++)
       fprintf(g,"%d ",*it+1);
       fprintf(g,"\n");
     }

}

int main()
{
    int i;
    read();
    used.resize(n);
    used.assign(used.size(),0);
    for(i=0;i<n;i++)
     if(!used[i])
       DFP(i);

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

    for(;discovered.size();discovered.pop_back())
       if(where[discovered.back()]==-1)
       {
           DFM(discovered.back(),count);
           count++;
       }
    for(i=0;i<n;i++)
      G[where[i]].push_back(i);

    print();

    return 0;
}