Cod sursa(job #3377135)

Utilizator TeogaloiuTeodor Galoiu Teogaloiu Data 21 noiembrie 2026 19:44:08
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <vector>
#include <algorithm>
using namespace std;
ifstream cin ("biconex.in");
ofstream cout ("biconex.out");
int tim[100001];
int low[100001];
int ctr=0;
int currentTime=1;
vector <int> v[100001];
vector <pair<int, int>> st;
vector <vector<int>> bccs;
void build(int start, int p = 0)
{
    low[start] = tim[start] = currentTime++;

    for(int next : v[start])
    {
        if(next == p) continue;

        if(tim[next] != 0) {
            low[start] = min(low[start], tim[next]);
            if(tim[next] < tim[start]) {
                st.push_back({start, next});
            }
        }
        else {
            st.push_back({start, next});
            build(next, start);
            low[start] = min(low[start], low[next]);

            if(low[next] >= tim[start]) {
                ctr++;
                vector<int> bcc;
                while(true) {
                    pair<int, int> edge = st.back();
                    st.pop_back();
                    bcc.push_back(edge.first);
                    bcc.push_back(edge.second);
                    if(edge == make_pair(start, next)) break;
                }
                sort(bcc.begin(), bcc.end());
                bcc.erase(unique(bcc.begin(), bcc.end()), bcc.end());
                bccs.push_back(bcc);
            }
        }
    }
}

void tarjan(){
    build(1, 0);
    cout << ctr << '\n';
    for(const auto& bcc : bccs) {
        for(int node : bcc) {
            cout << node << ' ';
        }
        cout << '\n';
    }
}

int main() {
    int n, m;
    if (!(cin >> n >> m)) return 0;
    for(int i = 1; i <= m; i++) {
        int a, b;
        cin >> a >> b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    tarjan();
    return 0;
}