Cod sursa(job #3234055)

Utilizator betybety bety bety Data 6 iunie 2024 10:42:47
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.92 kb
#include <bits/stdc++.h>
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");
const int lim = 1e5 + 4;
vector<int> vec[lim];
vector<int> rev[lim];
stack<int> topo;
int n, m, x, y;
bool ok[lim];
void df(int nod) {
	ok[nod] = true;
	for (int x : vec[nod]) {
		if (!ok[x]) {
			df(x);
		}
	}
	topo.push(nod);
}
vector<int> ans[lim];
int cnt;
void comp(int nod) {
	ok[nod] = true;
	ans[cnt].push_back(nod);
	for (int x : rev[nod]) {
		if (!ok[x]) {
			comp(x);
		}
	}
}
int main() {
	in >> n >> m;
	while (m--) {
		in >> x >> y;
		vec[x].push_back(y);
		rev[y].push_back(x);
	}
	for (int i = 1; i <= n; ++i) {
		if (!ok[i]) {
			df(i);
		}
	}
	memset(ok, 0, sizeof(ok));
	while (!topo.empty()) {
		int curr = topo.top();
		topo.pop();
		if (ok[curr]) {
			continue;
		}
		++cnt;
		comp(curr);
	}
	out << cnt << '\n';
	for (int i = 1; i <= cnt; ++i) {
		for (int a : ans[i]) {
			out << a << ' ';
		}
		out << '\n';
	}
	return 0;
}