Cod sursa(job #3300780)

Utilizator MihaiZ777MihaiZ MihaiZ777 Data 18 iunie 2025 23:36:18
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 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> nGraph[MAXN];
vector<int> tGraph[MAXN];
vector<vector<int>> ctcs;
bool visited[MAXN];

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

void DFS(int node, vector<int> graph[], vector<int>& path) {
	visited[node] = true;
	
	for (int newNode : graph[node]) {
		if (visited[newNode]) {
			continue;
		}
		DFS(newNode, graph, path);
	}
	path.push_back(node);
}

void Solve() {
	vector<int> path;
	for (int i = 1; i <= n; i++) {
		if (visited[i]) {
			continue;
		}
		DFS(i, nGraph, path);
	}
	memset(visited, false, sizeof(visited));

	vector<int> ctc;
	while (!path.empty()) {
		int node = path.back();
		path.pop_back();
		if (visited[node]) {
			continue;
		}

		DFS(path.back(), tGraph, ctc);
		ctcs.push_back(ctc);
		ctc.clear();
	}

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

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