Cod sursa(job #2629731)

Utilizator danserboiSerboi Florea-Dan danserboi Data 22 iunie 2020 14:59:59
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#include <unordered_set>
using namespace std;

const int kNmax = 100005;

class Task {
 public:
	void solve() {
		read_input();
		print_output(get_result());
	}

 private:
	int n;
	int m;
	vector<int> adj[kNmax];
	unordered_set<int> set;
	vector<int> component;

	struct Edge {
		int x;
		int y;
	};

	Edge e;

	void read_input() {
		ifstream fin("biconex.in");
		fin >> n >> m;
		for (int i = 1, x, y; i <= m; i++) {
			fin >> x >> y;
			adj[x].push_back(y);
			adj[y].push_back(x);
		}
		fin.close();
	}

	void dfsBC(int u, vector<int> &idx, vector<int> &low, int p, 
			stack<Edge> &s, vector<vector<int>> &sol, int &timp) {
		idx[u] = timp;
		low[u] = timp;
		timp++;
		int x, y;
		for (auto v: adj[u]) {
			if (p != v) {
				if (idx[v] == -1) {
					e.x = u; e.y = v;
					s.push(e);
					dfsBC(v, idx, low, u, s, sol, timp);
					low[u] = min(low[u], low[v]);

					if (low[v] >= idx[u]) {
						set.clear();
						component.clear();
						do {
							x = s.top().x;
							y = s.top().y;
							set.insert(x);
							set.insert(y);
							s.pop();
						} while ((x != u || y != v));

						for (auto e: set) {
							component.emplace_back(e);
						}
						//component.insert(component.end(), set.begin(), set.end());
						sol.emplace_back(component);
					}
 
				} else {
					low[u] = min(low[u], idx[v]);
				}
			}
		}
	}

	vector<vector<int>> get_result() {
		vector<vector<int>> sol;
		vector<int> idx(n + 1, -1);
		vector<int> low(n + 1, 0);
		stack<Edge> s;
		int p = 0;
		int timp = 0;
		for (int i = 1; i <= n; i++) {
			if (idx[i] == -1) {
				dfsBC(i, idx, low, p, s, sol, timp);
			}
		}

		return sol;
	}

	void print_output(vector<vector<int>> result) {
		ofstream fout("biconex.out");
		fout << result.size() << '\n';
		for (const auto& bc : result) {
			for (int nod : bc) {
				fout << nod << ' ';
			}
			fout << '\n';
		}
		fout.close();
	}
};

int main() {
	Task *task = new Task();
	task->solve();
	delete task;
	return 0;
}