Cod sursa(job #2667597)

Utilizator marianeacsuNeacsu Maria marianeacsu Data 3 noiembrie 2020 17:45:47
Problema Componente tare conexe Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb

#include <fstream>
#include <vector>
#define N 100005

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

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

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++)
    { 
        y = muchii[x][i];
        if (viz[y] == 0)
            DFS(y);
    }
    S[++top] = x;
}


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


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 (top > 0)
    {
        x = S[top]; top--;
        if (vizT[x]==0)
        {
            ct++;
            DFST(x);
        }
    }
    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;
}