Cod sursa(job #3311686)

Utilizator yellowGreenFatu Mihai yellowGreen Data 23 septembrie 2025 18:32:07
Problema Componente biconexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include <fstream>
#include <vector>
#include <set>
#include <stack>

using namespace std;
ifstream cin("biconex.in");
ofstream cout("biconex.out");
int n,m;
vector<int> G[100005];
int idx[100005],low[100005],cnt,v[100005],t[100005];
stack<pair<int,int>> st;
vector<set<int>> CBC;
set<int> c;
void extractCBC(int a,int b)
{
    c.clear();
    while(!st.empty())
    {
        auto [x,y]=st.top();
        st.pop();
        c.insert(x);
        c.insert(y);
        if(a==x && b==y)
            break;
    }
    CBC.push_back(c);
}
void dfs(int x)
{
    idx[x]=low[x]=++cnt;
    v[x]=1;
    for(auto y:G[x])
    {
        if(y==t[x]) continue;
        if(!v[y])
        {
            t[y]=x;
            st.push({x,y});
            dfs(y);
            low[x]=min(low[x],low[y]);
            if(low[y]>=idx[x])
                extractCBC(x,y);
        }
        else
            low[x]=min(low[x],low[y]);
    }
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin>>x>>y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    for(int i=1;i<=n;i++)
    {
        if(!v[i])
            dfs(i);
    }
    cout<<CBC.size()<<"\n";
    for(auto x:CBC)
    {
        for(auto y:x)
            cout<<y<<" ";
        cout<<"\n";
    }
    return 0;
}