Cod sursa(job #3183765)

Utilizator AndreiMLCChesauan Andrei AndreiMLC Data 13 decembrie 2023 09:53:54
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <stack>
#include <cmath>
#include <vector>
using namespace std;

ifstream f("ctc.in");
ofstream g("ctc.out");

const int nmax = 100005;
int n, m;
vector<int>G[nmax], GI[nmax];
bool viz[nmax];
stack<int>lista;
vector<vector<int>>componente;
bool adaugat[nmax];

void dfs(int nod)
{
	viz[nod] = 1;
	for (auto nbr : G[nod])
	{
		if (!viz[nbr])
		{
			dfs(nbr);
		}
	}
	lista.push(nod);
}

void assign(int nod, int tatic)
{
	adaugat[nod] = 1;
	componente[tatic].push_back(nod);
	for (auto nbr : GI[nod])
	{
		if (!adaugat[nbr])
		{
			assign(nbr, tatic);
		}
	}
}

int main()
{
	f >> n >> m;
	for (int i = 1; i <= m; i++)
	{
		int x, y;
		f >> x >> y;
		G[x].push_back(y);
		GI[y].push_back(x);
	}
	for (int i = 1; i <= n; i++)
	{
		if (!viz[i])
		{
			dfs(i);
		}
	}
	componente.resize(n+1);
	int total = 0;
	while (!lista.empty())
	{
		if (!adaugat[lista.top()])
		{
			assign(lista.top(), lista.top());
			total++;
		}
		lista.pop();
	}
	g << total << '\n';
	for (int i = 1; i <= n; i++)
	{
		if (!componente[i].empty())
		{
			for (auto it : componente[i])
			{
				g << it << ' ';
			}
			g << '\n';
		}
	}
}