Cod sursa(job #2781099)

Utilizator guzgandemunteIonescu Laura guzgandemunte Data 8 octombrie 2021 14:30:05
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.41 kb
#include <bits/stdc++.h>
#include <fstream>
#define VMAX 100000
using namespace std;

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

vector <int> adj[VMAX];
vector <int> aux[VMAX];
vector <int> component;
vector < vector <int> > toate;

int V, E, x, y;
stack <int> st;
bool vis[VMAX];

void DFS(int u)
{
    vis[u] = true;
    for (auto w:adj[u])
        if (!vis[w]) DFS(w);
    st.push(u);
}

void DFS_2(int u)
{
    vis[u] = true;
    component.push_back(u);
    for (auto w:aux[u])
        if (!vis[w]) DFS_2(w);
}

int main()
{
    fin >> V >> E;

    for (int i = 0; i < E; i++)
    {
        fin >> x >> y;
        x--, y--;
        adj[x].push_back(y);
    }

    for (int i = 0; i < V; i++)
        if (vis[i] == false) DFS(i);

    for (int i = 0; i < V; i++)
        for (auto j : adj[i])
        aux[j].push_back(i);

    for (int i = 0; i < V; i++)
        vis[i] = false;

    int nr = 0;

    while (!st.empty())
    {
        if (vis[st.top()] == false)
        {
            component.clear();
            DFS_2(st.top());
            toate.push_back(component);
            nr++;

        }
        st.pop();
    }

    fout << nr << endl;

    for (int i = 0; i < toate.size(); i++)
    {
        for (auto elem:toate[i])
            fout << elem + 1 << " ";
        fout << endl;
    }

    fin.close();
    fout.close();
    return 0;
}