Cod sursa(job #2336279)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 4 februarie 2019 22:43:42
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <iostream>
#include <stack>
#include <vector>
#include <fstream>
#define Nmax 100005

using namespace std;

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

vector <int> D[Nmax], I[Nmax];
vector <int> sol[Nmax];
stack <int> st;
int n, m, x, y;
int seen[Nmax], ans;

void dfs(int x)
{
    seen[x]=1;
    for (int i = 0, l=D[x].size(); i < l; i++)
    {
        int y=D[x][i];
        if(seen[y] == 1) continue;
        dfs(y);
    }
    st.push(x);
}

void dfsI(int x)
{
    seen[x]=-1;
    for (int i = 0, l=I[x].size(); i < l; i++)
    {
        int y=I[x][i];
        if(seen[y] == -1) continue;
        dfsI(y);
    }
    sol[ans].push_back(x);
}

int main()
{
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        f >> x >> y;
        D[x].push_back(y);
        I[y].push_back(x);
    }
    for (int i = 1; i <= n; i++)
        if(seen[i] == 0)
            dfs(i);

    while(!st.empty())
    {
        if(seen[st.top()] == -1)
        {
            st.pop();
            continue;
        }
        ans++;
        dfsI(st.top());
        st.pop();
    }
    g << ans << '\n';
    for (int i = 1; i <= ans; i++)
    {
        for (int j = 0, l=sol[i].size(); j < l; j++)
            g << sol[i][j] << " ";
        g << '\n';
    }

}