Cod sursa(job #2725158)

Utilizator MoiseVictor123Moise victor MoiseVictor123 Data 18 martie 2021 15:08:40
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb


//Algoritmul Kosaraju-Sharir
#include <fstream>
#include <stack>
#include <vector>
#include <algorithm>

using namespace std;

ifstream in ("ctc.in");
ofstream out ("ctc.out");

const int N = 100001;

int n;
int m;
int nc = 0;
vector<int> a[N];
vector<int> a_t[N];
stack<int> st;
bool viz[N];
bool viz_t[N];
vector<int> ctc[N];

void dfs(int x) {
	viz[x] = true;
	for (auto y : a[x]) {
		if (!viz[y]) {
			dfs(y);
		}
	}
	st.push(x);
}

void dfs_t(int x) {
	ctc[nc].push_back(x);
	viz_t[x] = true;
	for (auto y : a_t[x]) {
		if (!viz_t[y]) {
			dfs_t(y);
		}
	}
}

int main() {
	in >> n >> n;
	for (int i = 0; i < n; i++) {
		int x;
		int y;
		in >> x >> y;
		a[x].push_back(y);
		a_t[y].push_back(x);
	}
	for (int i = 1; i <= n; i++) {
		if (!viz[i]) {
			dfs(i);
		}
	}
	while (!st.empty()) {
		int x = st.top();
		st.pop();
		if (!viz_t[x]) {
			nc++;
			dfs_t(x);
		}
	}
	int k = 0;
	for (int i = 1; i <= nc; i++) {
		if (ctc[i].size() > 1) {
			k++;
		}
	}
	out << k << "\n";
	for (int i = 1; i <= nc; i++) {
		sort(ctc[i].begin(), ctc[i].end());
		if (ctc[i].size() > 1) {
			for (auto y : ctc[i]) {
			out << y << " ";
		}
		out << "\n";
		}
		
	}
}