Cod sursa(job #2667632)

Utilizator marianeacsuNeacsu Maria marianeacsu Data 3 noiembrie 2020 18:20:22
Problema Componente tare conexe Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb

#include <fstream>
#include <vector>
#include <stack>
#include <string.h>
#define N 100005

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

int n, m, viz[N], vizT[N], ct;
vector <int> muchii[N]; //pt graful initial
vector <int> muchiiT[N]; //pt graful transpus
vector <int> sol[N];
stack <int> S;

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

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


void DFST(int x)
{   
    int y, i;
    vizT[x] = 1;
    sol[ct].push_back(x);
    for (i = 0; i < muchiiT[x].size(); i++)
        if (vizT[muchiiT[x][i]] == 0)
            DFST(muchiiT[x][i]);
   
}


void CompTareConexe()
{  /// aplicam DFS pe graful initial si memoram nodurile in ordinea timpilor de final intr-o stiva
    int i, x, ct = 0, j;
    for (i = 1; i <= n; i++)
        if (viz[i]==0) 
            DFS(i);
    /// aplica DFS pe graful transpus in ordinea inversa a timpilor de final
    while (S.empty()==0)
    {
        if (vizT[S.top()]==0)
        {
            ct++;
            DFST(S.top());
        }
        S.pop();
    }
    fout << ct << "\n";
    for (i = 1; i <= ct; i++)
    {
        for (j = 0; j < sol[i].size(); j++)
            fout << sol[i][j] << " ";
        fout << "\n";
    }
}


int main()
{
    Citire();
    CompTareConexe();
 
    return 0;
}