Cod sursa(job #1444398)

Utilizator cernat.catallinFMI Cernat Catalin Stefan cernat.catallin Data 29 mai 2015 18:41:20
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

std::ifstream in("biconex.in");
std::ofstream out("biconex.out");

const int nmax = 100005;

vector<int> graph[nmax];
stack<int, vector<int>> st;
vector<vector<int>> solutions;

int low[nmax];
int found[nmax];
int n, m;
int counter;

void get_solution(int x, int y) {
    solutions.push_back(vector<int>());
    while (st.top() != y) {
        solutions.back().push_back(st.top());
        st.pop();
    }
    st.pop();
    solutions.back().insert(solutions.back().end(), { y, x });
}

void dfs(int u) {
    found[u] = low[u] = ++counter;
    st.push(u);
    for (auto v : graph[u])
        if (!found[v]) {
            dfs(v);
            low[u] = min(low[u], low[v]);
            if (low[v] >= found[u])
                get_solution(u, v);
        }
        else
            low[u] = min(low[u], found[v]);
}

int main() {
    int x, y;

    in >> n >> m;
    for (int i = 0; i < m; ++i) {
        in >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    dfs(1);

    out << solutions.size() << '\n';
    for (auto &comp : solutions) {
        for (auto u : comp)
            out << u << ' ';
        out << '\n';
    }

    return 0;
}