Cod sursa(job #2781454)

Utilizator guzgandemunteIonescu Laura guzgandemunte Data 9 octombrie 2021 16:44:56
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
#include <fstream>
#define VMAX 100000
using namespace std;
ifstream fin("biconex.in");
ofstream fout("biconex.out");

vector <int> adj[VMAX];
int V, E, x, timp, y;
int disc[VMAX], low[VMAX];
bool artPoint[VMAX];
stack < pair <int, int> > edges;
vector < vector <int> > allBcc;

int nrBcc;

void getBcc(int u, int w)
{
    vector <int> oneBcc;
    pair <int, int> currEdge = make_pair(-1, -1);

    while (currEdge.first != u || currEdge.second != w)
    {
        currEdge = edges.top();
        edges.pop();
        oneBcc.push_back(currEdge.first);
        oneBcc.push_back(currEdge.second);
    }

    allBcc.push_back(oneBcc);
}

void DFSap(int u, int parent = -1)
{
    disc[u] = low[u] = ++timp;
    for (auto w : adj[u])
    {
        if (parent == w) continue;
        if (!disc[w])
        {
            edges.push(make_pair(u, w));
            DFSap(w, u);
            low[u] = min(low[u], low[w]);
            if (low[w] >= disc[u])
                getBcc(u, w);
        }
        else if (disc[w] < disc[u])
        {
            edges.push(make_pair(u, w));
            low[u] = min(low[u], disc[w]);
        }
    }
}

int main()
{
    ios_base::sync_with_stdio(false);
    fin.tie(0);
    fout.tie(0);

    fin >> V >> E;

    while (E--)
    {
        fin >> x >> y;
        x--, y--;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }

    for (int i = 0; i < V; ++i)
    {
        if (!disc[i]) DFSap(i);
        timp = 0;
    }

    fout << allBcc.size() << '\n';

    for (auto i:allBcc)
    {
        sort(i.begin(),i.end());
        i.erase(unique(i.begin(), i.end()), i.end());
        for (auto j:i)
            fout << j + 1 << " ";
        fout << '\n';
    }

    fin.close();
    fout.close();

    return 0;
}

/*
5 5
0 2
1 2
1 0
0 3
3 4
*/

/*
5 6
1 2
2 3
1 3
3 4
4 5
5 3
*/

/*
8 9
1 2
2 3
3 4
4 1
1 5
5 6
6 7
7 5
7 8
*/