Cod sursa(job #2370051)

Utilizator Anastasia11Susciuc Anastasia Anastasia11 Data 6 martie 2019 10:29:33
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define Nmax 100005

using namespace std;

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

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

void dfs1(int x)
{
    used[x]=1;
    for (auto y:D[x])
    {
        if(used[y] == 1) continue;
        dfs1(y);
    }
    st.push(x);
}

void dfs2(int x)
{
    used[x]=-1;
    for (auto y:I[x])
    {
        if(used[y] == -1) continue;
        dfs2(y);
    }
    sol[ctc].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(used[i] == 0)
        {
            dfs1(i);
        }

    while(!st.empty())
    {
        if(used[st.top()] == -1)
        {
            st.pop();
            continue;
        }
        dfs2(st.top());
        st.pop();
        ctc++;
    }
    g << ctc << '\n';
    for (int i = 0; i < ctc; i++)
    {
        for (auto y:sol[i])
            g << y << ' ';
        g << '\n';
    }

    return 0;
}