Cod sursa(job #2667551)

Utilizator marianeacsuNeacsu Maria marianeacsu Data 3 noiembrie 2020 17:09:33
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 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

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


void DFST(int x)
{
    vizT[x] = ct;
    for (auto i : muchiiT[x])
    {
        if (vizT[i] == 0)
            DFST(i);
    }
   
}


void CompTareConexe()
{  /// aplicam DFS pe graful initial si memoram nodurile in ordinea timpilor de final intr-o stiva
    int i, x, 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 = 1; j <= n; j++)
            if (vizT[j] == i)
                fout << j << " ";
        fout << "\n";
    }
   
}



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