Cod sursa(job #2045816)

Utilizator vladm98Munteanu Vlad vladm98 Data 22 octombrie 2017 21:27:21
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

vector <int> ctc[100001];
vector <int> graf[100001];
vector <int> igraf[100001];
vector <int> v;
bitset <100001> viz;
void dfs1 (int node)
{
	viz[node] = 1;
	for (auto x:graf[node])
		if (viz[x] == 0)
			dfs1(x);
	v.push_back(node);
}

void dfs2 (int node, int where)
{
	ctc[where].push_back(node);
	viz[node] = 0;
	for (auto x:igraf[node])
		if (viz[x])
			dfs2(x, where);
}
int main(int argc, char const *argv[])
{
	ifstream fin ("ctc.in");
	ofstream fout ("ctc.out");
	int n, m;
	fin >> n >> m;
	for (int i = 1; i<=m; ++i)
	{
		int x, y;
		fin >> x >> y;
		graf[x].push_back(y);
		igraf[y].push_back(x);
	}
	for (int i = 1; i<=n; ++i)
		if (viz[i] == 0)
			dfs1(i);
	int cate = 0;
	reverse(v.begin(), v.end());
	for (auto x:v)
		if (viz[x])
		{
			++cate;
			dfs2(x, cate);
		}
	cout << cate << '\n';
	for (int i = 1; i<=cate; ++i)
	{
		for (auto x:ctc[i])
			cout << x << ' ';
		cout << '\n';
	}
	return 0;
}