Cod sursa(job #2122514)

Utilizator alexandru822Bosinta Alexandru alexandru822 Data 5 februarie 2018 10:23:37
Problema Componente biconexe Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.82 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

ofstream out("biconex.out");
ifstream in("biconex.in");
ofstream tout("test.out");

const int N_MAX = 100000;
vector<int> neighbours[1 + N_MAX];
vector<vector<int>> components;
stack<pair<int, int>> dfs;
int n, depth[1 + N_MAX], height[1 + N_MAX];
bool visited[1 + N_MAX];

void read()
{
    int m;
    in >> n >> m;
    for(int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        neighbours[x].push_back(y);
        neighbours[y].push_back(x);
    }
    depth[1] = 1;
    height[1] = 1;
}

void cache(int x, int y)
{
    vector<int> curcomp;
    int tx, ty;
    do
    {
        tx = dfs.top().first;
        ty = dfs.top().second;
        dfs.pop();
        curcomp.push_back(tx);
        curcomp.push_back(ty);
    }while(tx != x | ty != y);
    components.push_back(curcomp);
}

void DFS(int node, int father)
{
    for(int m : neighbours[node])
    {
        if(m == father)
            continue;
        if(depth[m])
            height[node] = min(height[node], height[m]);
        else
        {
            dfs.push(make_pair(node,m));
            depth[m] = depth[node] + 1;
            height[m] = depth[m];
            DFS(m, node);
            height[node] = min(height[node], height[m]);
            if(height[m] >= depth[node])
                cache(node, m);
        }
    }
}

void print()
{
    out << components.size() << "\n";
    for(vector<int> m : components)
    {
        sort(m.begin(),m.end());
        auto it = unique(m.begin(),m.end());
        m.resize(distance(m.begin(),it));
        for(int r : m)
            out << r << " ";
        out << "\n";
    }
}

int main()
{
    read();
    DFS(1, 0);
    print();
    return 0;
}