Cod sursa(job #2602840)

Utilizator MariaCarminaCretu Maria Carmina MariaCarmina Data 17 aprilie 2020 23:11:27
Problema Componente biconexe Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.92 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <stack>

using namespace std;

const int kNmax = 100005;

struct Edge {
		short x;
		short y;
	};

int n, m;
vector<int> adj[kNmax];
bool visited[kNmax];
short idx[kNmax];
short low[kNmax];
int timer = 1;
vector<int> biconex_component[kNmax];
int num_component = 0;
stack<Edge> s;

void dfs(int node, int parent) {
    visited[node] = true;
    idx[node] = timer;
    low[node] = timer;
    timer++;
    for (auto next : adj[node]) {
        if (next != parent) {
				if (visited[next] == false) {
                    Edge edge;
					edge.x = node;
					edge.y = next;
                    s.push(edge);
					dfs(next, node);
					low[node] = min(low[node], low[next]);
					if (low[next] >= idx[node]) {
                        num_component++;
                        while (!s.empty() && s.top().x != node) {
						    Edge biconex_edge = s.top();
                            s.pop();
                            biconex_component[num_component].push_back(biconex_edge.y);
                        }
                        biconex_component[num_component].push_back(node);
                        biconex_component[num_component].push_back(next);
                        s.pop();
					}
				} else {
					low[node] = min(low[node], low[next]);
				}
    }
}
}

int main() {
    ifstream f("biconex.in");
    ofstream g("biconex.out");
	f >> n >> m;
	for (int i = 1, x, y; i <= m; i++) {
		f >> x >> y;
		adj[x].push_back(y);
		adj[y].push_back(x);
	}

    for(int i = 1; i <= n; ++i) {
        visited[i] = false;
    }

    for (int i = 1; i <= n; ++i) {
        if (visited[i] == false) {
            dfs(i, 0);
        }
    }
    g << num_component << endl;
    for (int i = 1; i <= num_component; ++i) {
        for (auto j : biconex_component[i]) {
            g << j << " ";
        }
        g << endl;
    }

}