Cod sursa(job #2314342)

Utilizator AlexTudorAlex Brinza AlexTudor Data 8 ianuarie 2019 12:54:08
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <bits/stdc++.h>
using namespace std;

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

const int NMAX=100005;

stack <int> S,S2;
vector <int> v[NMAX],v2[NMAX];
int viz[NMAX],viz2[NMAX];
int n,m;
int nr;

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

    fin.close();
}

void DFS(int x)
{
    int w;
    viz[x]=1;
    for(int i=0;i<v[x].size();++i)
    {
        w=v[x][i];
        if(viz[w]==0) DFS(w);
    }
    S.push(x);
    S2.push(x);
}


void nebunie()
{
    for(int i=1;i<=n;++i)
    {
        if(viz[i]==0) DFS(i);
    }
}

void DFS2(int u, int mama)
{
    int w;
    viz2[u]=1;
    if(mama==1) fout<<u<<" ";
    for(int i=0;i<v2[u].size();++i)
    {
        w=v2[u][i];
        if(viz2[w]==0) DFS2(w,mama);
    }
}

void stesh()
{
    int top;
   while(S.size()>0)
   {
       top=S.top(); S.pop();
       if(viz2[top]==0) {DFS2(top,0); nr++;}
   }

    for(int i=1;i<=n;++i) viz2[i]=0;

   fout<<nr<<" ";

   while(S2.size()>0)
   {
       top=S2.top(); S2.pop();
       if(viz2[top]==0) {fout<<"\n"; DFS2(top,1);}
   }

}


int main()
{
    read();
    nebunie();
    stesh();
    return 0;
}