Cod sursa(job #3300786)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 19 iunie 2025 00:37:32
Problema Componente tare conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <algorithm>
#include <cmath>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
#include <fstream>
#include <cstring>
using namespace std;

#define fast_io ios::sync_with_stdio(0); cin.tie(0); do{}while(0)
typedef long long ll;

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

const int MAXN = 1e5 + 5;

int n, m;
vector<int> graph[MAXN];
vector<int> path;
int discovery[MAXN];
int link[MAXN];
bool inStack[MAXN];
vector<vector<int>> ctcs;
int t;

void ReadData() {
	fin >> n >> m;
	int a, b;
	for (int i = 0; i < m; i++) {
		fin >> a >> b;
		graph[a].push_back(b);
	}
}

void DFS(int node) {
	t++;
	path.push_back(node);
	discovery[node] = t;
	link[node] = t;
	inStack[node] = true;

	for (int newNode : graph[node]) {
		if (!discovery[newNode]) {
			DFS(newNode);
			link[node] = min(link[newNode], link[node]);
		} else if (inStack[newNode]) {
			link[node] = min(link[node], discovery[newNode]);
		}
	}

	if (discovery[node] == link[node]) {
		vector<int> ctc;
		while (!path.empty() && path.back() != node) {
			ctc.push_back(path.back());
			inStack[path.back()] = false;
			path.pop_back();
		}
		ctc.push_back(node);
		path.pop_back();

		ctcs.push_back(ctc);
	}
}

void Solve() {
	for (int i = 1; i <= n; i++) {
		if (discovery[i]) {
			continue;
		}
		DFS(i);
	}

	fout << ctcs.size() << '\n';
	for (auto c : ctcs) {
		for (int x : c) {
			fout << x << ' ';
		}
		fout << '\n';
	}
}

int main() {
		ReadData();
		Solve();
		return 0;
}