Cod sursa(job #2704384)

Utilizator razvan9310FMI - Razvan Damachi razvan9310 Data 10 februarie 2021 14:41:08
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.85 kb
#include <bits/stdc++.h>
using namespace std;

void dfs_1(const int root,
		  const vector<vector<int>>& g,
		  vector<bool>& seen,
		  stack<int>& nodes_finished) {
	seen[root] = true;
	for (const int adj : g[root]) {
		if (!seen[adj]) {
			dfs_1(adj, g, seen, nodes_finished);
		}
	}
	nodes_finished.push(root);
}

void dfs_2(const int root,
           const vector<vector<int>>& g,
           vector<int>& sccs,
           const int curr_scc) {
	sccs[root] = curr_scc;
	for (const int adj : g[root]) {
		if (sccs[adj] == -1) {
			dfs_2(adj, g, sccs, curr_scc);
		}
	}
}

vector<int> compute_sccs(const int n, const vector<vector<int>>& g) {
	vector<bool> seen(n + 1, false);
	stack<int> nodes_finished;
	for (int i = 1; i <= n; ++i) {
		if (!seen[i]) {
			dfs_1(i, g, seen, nodes_finished);
		}
	}
	
	vector<vector<int>> gt(n + 1);
	for (int i = 1; i <= n; ++i) {
		for (const int adj : g[i]) {
			gt[adj].push_back(i);
		}
	}
	
	vector<int> sccs(n + 1, -1);
	int next_scc = 1;
	while (!nodes_finished.empty()) {
		int node = nodes_finished.top();
		nodes_finished.pop();
		if (sccs[node] == -1) {
			dfs_2(node, gt, sccs, next_scc);
			++next_scc;
		}
	}
	
	return sccs;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(nullptr);
	
	ifstream in("ctc.in");
	in.tie(nullptr);
	ofstream out("ctc.out");
	out.tie(nullptr);
	
	int n, m;
	in >> n >> m;
	vector<vector<int>> g(n + 1);
	for (int i = 0; i < m; ++i) {
		int u, v;
		in >> u >> v;
		g[u].push_back(v);
	}
	
	vector<int> sccs = compute_sccs(n, g);
	int scc_count = 0;
	for (int i = 1; i <= n; ++i) {
		scc_count = max(scc_count, sccs[i]);
	}
	vector<vector<int>> scc_to_nodes(scc_count + 1);
	for (int i = 1; i <= n; ++i) {
		scc_to_nodes[sccs[i]].push_back(i);
	}
	out << scc_count << "\n";
	for (const vector<int>& nodes : scc_to_nodes) {
		for (const int node : nodes) {
			out << node << " ";
		}
		out << "\n";
	}
}