Cod sursa(job #3030957)

Utilizator roxana13.Ghitan Roxana roxana13. Data 18 martie 2023 02:43:29
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.38 kb
#include <fstream>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#define nmax 100005

using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

int  n, m, x, y, v, t, nrc;
int  d[nmax];
stack <int> st;
vector<int> G[nmax], L[nmax], V[nmax];

void dfs(int x)
{
    d[x] = 1;
    int nr = G[x].size();
    for (int i = 0; i < nr; i++)
    {
        if (d[G[x][i]] == 0)/// muchie de arbore nevizitata
            dfs(G[x][i]);
    }
    st.push(x);/// este vf de ctc si o adaug in stiva
}

void dfss(int x)
{
    d[x] = 2;
    V[nrc].push_back(x); /// adauga vf in vect de comp conexe

    int nr = L[x].size();
    for (int i = 0; i < nr; i++) {
        if (d[L[x][i]] == 1)
            dfss(L[x][i]);
    }
}

int main()
{
    int x, y, m;
    f >> n >> m;
    for(int i=1; i<=m; i++)
    {
        f >> x >> y;
        G[x].push_back(y);
        L[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if (!d[i])
            dfs(i);

    while (!st.empty())
    {
        int r = st.top();//ultima comp conexa
        st.pop();
        if (d[r] == 1)
        {
            nrc++;
            dfss(r);
        }
    }
    g << nrc << '\n';
    for (int i = 1; i <= nrc; i++) {
        for (int j = 0; j < V[i].size(); j++)
            g << V[i][j] << ' ';
        g << '\n';
    }

    return 0;
}