Cod sursa(job #3216030)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 15 martie 2024 16:14:46
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define ff first
#define ss second
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define eb emplace_back


using namespace std;
const string TASK("biconex");
ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");
#define cin fin
#define cout fout

const int N = 1e5 + 9;

int n, m;
vvi G(N);

int low[N], lvl[N], idx;
stack<pii> stk;
vvi cbc;
vi c;

void extract(int x, int y)
{
    c.clear();
    while(true)
    {
        int a = stk.top().ff, b = stk.top().ss;
        stk.pop();

        c.pb(a), c.pb(b);

        if(a == x && b == y)break;
    }
    sort(c.begin(), c.end());
    c.erase(unique(c.begin(), c.end()), c.end());
    cbc.pb(c);
}

void Dfs(int x, int p = 0)
{
    low[x] = lvl[x] = ++idx;

    for(auto y : G[x])
    {
        if(y == p)continue;

        if(!lvl[y])
        {
            stk.push({x, y});

            Dfs(y, x);

            low[x] = min(low[x], low[y]);

            if(lvl[x] <= low[y])
                extract(x, y);
        }
        else low[x] = min(low[x], lvl[y]);
    }
}


int main()
{
    ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);

    cin >> n >> m;

    int x, y;
    for(int i = 1; i <= m; ++i)
    {
        cin >> x >> y;
        G[x].pb(y);
        G[y].pb(x);
    }

    for(int i = 1; i <= n; ++i)
        if(!lvl[i])
            Dfs(i);

    cout << cbc.size() << '\n';
    for(auto i : cbc)
    {
        for(auto j : i)
            cout << j << ' ';
        cout << '\n';
    }
    return 0;
}