Cod sursa(job #2853125)

Utilizator alextmAlexandru Toma alextm Data 19 februarie 2022 22:04:29
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 1e5 + 5;

int timer, nrc;
int low[MAXN], lvl[MAXN];
bool viz[MAXN];
vector<int> G[MAXN], comp[MAXN];
stack<pair<int,int>> st;

void DFS(int node, int father = 0) {
	viz[node] = 1;
	low[node] = lvl[node] = ++timer;

	for(int son : G[node])
		if(viz[son] == 0) {
			st.push({node, son});
			DFS(son, node);
			low[node] = min(low[node], low[son]);
			
			if(lvl[node] <= low[son]) {
				nrc++;
				while(st.top() != make_pair(node, son)) {
					comp[nrc].push_back(st.top().first);
					comp[nrc].push_back(st.top().second);
					st.pop();
				}
				
				comp[nrc].push_back(node);
				comp[nrc].push_back(son);
				st.pop();
			}
		}
		else
			low[node] = min(low[node], lvl[son]);
}

int main() {
	ifstream cin("biconex.in");
	ofstream cout("biconex.out");
	
	int n, m;
	cin >> n >> m;
	
	while(m--) {
		int x, y;
		cin >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
	
	for(int i = 1; i <= n; i++)
		if(!viz[i])
			DFS(i);
			
	cout << nrc << '\n';
	for(int i = 1; i <= nrc; i++) {
		sort(comp[i].begin(), comp[i].end());
		for(int j = 0; j < (int)comp[i].size(); j++)
			if(j == 0 || comp[i][j] != comp[i][j - 1])
				cout << comp[i][j] << ' ';
		cout << '\n';
	}
	
	return 0;
}