Cod sursa(job #2606445)

Utilizator AndreiFlorescuAndrei Florescu AndreiFlorescu Data 27 aprilie 2020 19:42:33
Problema Componente biconexe Scor 66
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.01 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];
	int idx[kNmax], low[kNmax];
	stack<pair <int, 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 v, int u) {
		vector<int> cur_comp;
		int c_v, c_u;

		do {
			c_v = stk.top().first;
			c_u = stk.top().second;

			stk.pop();

			cur_comp.push_back(c_v);
			cur_comp.push_back(c_u);

		} while (c_v != v && c_u != u);

		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(make_pair(node, *it));
				cut_vertex(*it, node, time + 1);

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

				if (low[*it] >= idx[node]) {
					make_bicon_comp(n, *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.
		*/

		cut_vertex(1, 0, 1);

	}

	void print_output() {
		ofstream fout("biconex.out");
		fout << result.size() << '\n';
		for (auto& ctc : result) {
			sort(ctc.begin(), ctc.end());
        	ctc.erase(unique(ctc.begin(), ctc.end()), ctc.end());
			for (int nod : ctc) {
				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;
}