Cod sursa(job #2606455)

Utilizator AndreiFlorescuAndrei Florescu AndreiFlorescu Data 27 aprilie 2020 20:03:55
Problema Componente biconexe Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <bits/stdc++.h>
using namespace std;

const int kNmax = 100005;

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

private:
	int n;
	int m;
	vector<int> adj[kNmax];
	vector<int> idx, low;
	stack<int> stk;
	vector <vector <int> > result;

	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();
	}

	int min(int a, int b) {
		return a < b ? a : b;
	}

	void make_bicon_comp(int node, int son) {
		vector<int> cur_comp;
		int cur;

		do {
			cur = stk.top();

			stk.pop();

			cur_comp.push_back(cur);

		} while (cur != son);

		cur_comp.push_back(node);
		result.push_back(cur_comp);
	}

	void cut_vertex(int node, int parent, int time) {
		idx[node] = low[node] = time;

		vector <int>::iterator it;
		for (it = adj[node].begin(); it != adj[node].end(); it++) {
			if (*it == parent) {
				continue;
			}

			if (idx[*it] == 0) {
				stk.push(*it);
				cut_vertex(*it, node, time + 1);

				low[node] = min(low[node], low[*it]);

				if (low[*it] >= idx[node]) {
					make_bicon_comp(node, *it);
				}
			} else {
				low[node] = min(low[node], idx[*it]);
			}
		}
	}

	void get_result() {
		/*
		TODO: Gasiti nodurile critice ale grafului neorientat stocat cu liste
		de adiacenta in adj.
		*/

		idx.resize(n + 1);
    	low.resize(n + 1);
    	idx.assign(n + 1, 0);

		cut_vertex(1, 0, 1);

	}

	void print_output() {
		ofstream fout("biconex.out");
		fout << result.size() << '\n';
		for (int i = 0; i < result.size(); i++) {
			sort(result[i].begin(), result[i].end());
			for (int nod : result[i]) {
				fout << nod << ' ';
			}
			fout << '\n';
		}
		fout.close();
	}
};

// Please always keep this simple main function!
int main() {
	// Allocate a Task object on heap in order to be able to
	// declare huge static-allocated data structures inside the class.
	Task *task = new Task();
	task->solve();
	delete task;
	return 0;
}