Cod sursa(job #3183183)

Utilizator octavian202Caracioni Octavian Luca octavian202 Data 10 decembrie 2023 21:52:50
Problema Componente biconexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <cstring>
#include <stack>

using namespace std;

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

const int NMAX = 1e5 + 5;
int dfn[NMAX], low[NMAX], n, m, cerinta, nr_componente = 0;
vector<int> g[NMAX], comp[NMAX];
vector<int> punct_de_articulatie;
vector<pair<int, int> > punti;

int cnt = 0;
stack<int> st;
void dfs(int curr, int prv) {
    dfn[curr] = low[curr] = ++cnt;
    st.push(curr);

    for (auto nxt : g[curr]) {
        if (nxt == prv)
            continue;
        if (dfn[nxt] == -1) { // nevizitat (muchie de arbore)
            dfs(nxt, curr);
            low[curr] = min(low[curr], low[nxt]);


            if (low[nxt] >= dfn[curr]) {
                if (curr != 1)
                    punct_de_articulatie.push_back(curr);

                punti.push_back(make_pair(curr, nxt));

                nr_componente++;
                while (!st.empty() && st.top() != curr) {
                    comp[nr_componente].push_back(st.top());
                    st.pop();
                }
                if (!st.empty()) {
                    comp[nr_componente].push_back(st.top());
                }
            }
        } else { // vizitat (muchie de intoarcere)
            low[curr] = min(low[curr], dfn[nxt]);
        }
    }
}

int main() {

    fin >> cerinta >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;

        g[x].push_back(y);
        g[y].push_back(x);
    }

    memset(low, -1, sizeof(low));
    memset(dfn, -1, sizeof(dfn));

    dfs(1, -1);
//    if (g[1].size() >= 2) {
//        nr_componente++;
//        while (!st.empty()) {
//            comp[nr_componente].push_back(st.top());
//            st.pop();
//        }
//    }

    if (cerinta == 1) {
        fout << nr_componente << '\n';
        for (int i = 1; i <= nr_componente; i++) {
            fout << comp[i].size() << ' ';
            for (auto x : comp[i])
                fout << x << ' ';
            fout << '\n';
        }
    } else if (cerinta == 2) {
        fout << punct_de_articulatie.size() << '\n';
        for (auto x : punct_de_articulatie) {
            fout << x << ' ';
        }
    } else {
        fout << punti.size() << '\n';
        for (auto punte : punti) {
            fout << punte.first << ' ' << punte.second << '\n';
        }
    }


    return 0;
}