Cod sursa(job #2605808)

Utilizator Chr1styDescultu Cristian Chr1sty Data 25 aprilie 2020 20:30:55
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>
using namespace std;

const int kNmax = 100005;

class Task {
public:
	void solve() {
		read_input();
		get_result();
		print_output();
	}

private:
	int n;
	int m;
	vector<int> adj[kNmax];
	vector<int> adj_trans[kNmax];
	vector<vector<int>> sol;
	vector<int> sortorder;
	int contor = 0;
	vector<int> visited;
	vector<int> visitedT;

	void read_input() {
		ifstream fin("ctc.in");
		fin >> n >> m;
		visited = vector<int>(n + 1, 0);
		visitedT = vector<int>(n + 1, 0);
		for (int i = 1, x, y; i <= m; i++) {
			fin >> x >> y;
			adj[x].push_back(y);
			adj_trans[y].push_back(x);
		}
		fin.close();
	}

	void get_result() {
		kosaraju();
	}
	void kosaraju() {
		sortorder.push_back(-1);
		for (int i = 1; i <= n; ++i) {
			if (!visited[i]) {
				dfs(i);
			}
		}

		for (int i = n; i >= 1; --i) {
			if (!visitedT[sortorder[i]]) {
				contor++;
				dfst(sortorder[i]);

			}
		}
	}

	void dfs(int nod) {
		visited[nod] = 1;
		for (auto &neigh : adj[nod]) {
			if (!visited[neigh]) {
				dfs(neigh);
			}
		}
		sortorder.push_back(nod);
	}

	void dfst(int nod) {
		visitedT[nod] = 1;
		sol[contor].push_back(nod);
		for (auto &neigh : adj_trans[nod]) {
			if (!visitedT[neigh]) {
				dfst(neigh);
			}
		}
	}

	void print_output() {
		ofstream fout("ctc.out");
		fout << contor << '\n';
		for (const auto& ctc : sol) {
			for (int nod : ctc) {
				fout << nod << ' ';
			}
			fout << '\n';
		}
		fout.close();
	}
};

// Please always keep this simple main function!
int main() {
	// Allocate a Task object on heap in order to be able to
	// declare huge static-allocated data structures inside the class.
	Task *task = new Task();
	task->solve();
	delete task;
	return 0;
}