Cod sursa(job #2189538)

Utilizator FrequeAlex Iordachescu Freque Data 28 martie 2018 16:17:27
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.83 kb
#include <iostream>
#include <fstream>
#include <cstring>
#include <vector>
#include <stack>

using namespace std;

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

const int NMAX = 1e5 + 5;
const int INF = 0x3f3f3f3f;

vector <int> graph[NMAX], tree[NMAX], comp[NMAX];
stack <int> s;
int n, m, timp, cnt;
int disc[NMAX], low[NMAX], father[NMAX];
bool vis[NMAX];

void dfs(int node)
{
    vis[node] = true;
    disc[node] = disc[father[node]] + 1;
    for (int next: graph[node])
        if (!vis[next])
        {
            father[next] = node;
            tree[node].push_back(next);
            s.push(next);
            dfs(next);

            if (low[next] >= disc[node])
            {
                ++cnt;
                while (s.top() != next)
                {
                    comp[cnt].push_back(s.top());
                    s.pop();
                }
                comp[cnt].push_back(s.top());
                s.pop();
            }
        }

    low[node] = INF;
    for (int next: tree[node]) low[node] = min(low[node], low[next]);
    for (int next: graph[node]) low[node] = min(low[node], disc[next]);
}

void write()
{
    fout << cnt << '\n';
    for (int i = 1; i <= cnt; ++i)
    {
        for (int j: comp[i])
            fout << j << " ";
        fout << father[comp[i][comp[i].size() - 1]] << '\n';
    }
}

void read()
{
    int x, y;

    fin >> n >> m;
    for (int i = 1; i <= m; ++i)
    {
        fin >> x >> y;
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    memset(disc, -1, sizeof(disc));
    memset(low, -1, sizeof(low));
    memset(father, -1, sizeof(father));
}

int main()
{
    read();

    for (int i = 1; i <= n; ++i)
        if (disc[i] == -1)
            dfs(i);

    write();

    return 0;
}