Cod sursa(job #1899370)

Utilizator dumitrualexAlex Dumitru dumitrualex Data 2 martie 2017 17:59:55
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
#define nmax 100000+5
using namespace std;

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

int N, M;
vector<int> graph[nmax]; // directed graph
vector<int> reversed[nmax]; // directed graph, reversed direction
stack<int> st; // our stack of nodes
bool visited[nmax];
vector<vector<int> > components;

void dfs1(int node)
{
    visited[node] = true;
    for (int i = 0; i < graph[node].size(); i++)
    {
        int neighbor = graph[node][i];

        if (!visited[neighbor])
            dfs1(neighbor);
    }
    st.push(node);
}

void formComponent(int node, const int & cmp_indx)
{
    visited[node] = true;
    components[cmp_indx].push_back(node);
    for (int i = 0; i < reversed[node].size(); i++)
    {
        int neighbor = reversed[node][i];

        if (!visited[neighbor])
            formComponent(neighbor, cmp_indx);
    }
}
int main()
{
    ios::sync_with_stdio(0);

    fin >> N >> M;
    for (int i = 1; i <= M; i++)
    {
        int x, y;
        fin >> x >> y;

        graph[x].push_back(y);
        reversed[y].push_back(x);
    }

    for (int i = 1; i <= N; i++)
        if (!visited[i])
            dfs1(i);

    for (int i = 1; i <= N; i++)
        visited[i] = false;

    while (!st.empty())
    {
        int node = st.top();
        st.pop();

        if (visited[node])
            continue;

        components.push_back(vector<int>());
        formComponent(node, components.size()-1);
    }

    fout << components.size() << '\n';
    for (auto it = components.begin(); it != components.end(); it++)
    {
        for (auto node = it->begin(); node != it->end(); node++)
            fout << *node << ' ';
        fout << '\n';
    }
    return 0;
}