Cod sursa(job #2798510)

Utilizator vasiliumirunamariaVasiliu Miruna-Maria vasiliumirunamaria Data 11 noiembrie 2021 13:50:17
Problema Sortare topologica Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.55 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
#define N 100005
using namespace std;

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



int nrc; 

class Graph {


public:
	static bool viz[N];
	static bool viz_t[N];
	int cost[N];
	stack <int> S;
	int n; //nr de varfuri
	int m; //nr de muchii

	vector <int> a[N];
	vector <int> c[N];
	vector <int> a_t[N];



	Graph(int n, int m)
	{
		this->n = n;
		this->m = m;
	}

	void Citire_orientat();
	void Citire_neorientat();
	void DFS(int x);
	void DFS_T(int x, int ct);
	void CompTConexe();
	void ParcurgereGraf();
	void BFS(int x);
	void SortTop();
	


};

bool Graph::viz[N] = { 0 };
bool Graph::viz_t[N] = { 0 };

void Graph::Citire_orientat()
{
	int i;
	int x, y;

	for (i = 0; i < m; i++)
	{
		fin >> x >> y;
		a[x].push_back(y);
		a_t[y].push_back(x);

	}
}

void Graph::Citire_neorientat()
{
	int i;
	int x, y;
	for (i = 1; i <= m; i++)
	{
		fin >> x >> y;
		a[x].push_back(y);
		a[y].push_back(x);
	}
}
void Graph::BFS(int x)
{
	queue <int> q;
	int k, i;
	viz[x] = 1;
	cost[x] = 0;
	q.push(x);

	while (!q.empty())
	{
		k = q.front();
		for (i = 0; i < a[k].size(); i++)
			if (!viz[a[k][i]])
			{
				q.push(a[k][i]);
				viz[a[k][i]] = 1;
				cost[a[k][i]] = cost[k] + 1;
			}

		q.pop();
	}

	for (i = 1; i <= n; i++)
		if (viz[i] == 0)
			fout << -1 << " ";
		else fout << cost[i] << " ";



}
void Graph::ParcurgereGraf()
{
	int i;
	for (i = 1; i <= n; i++)
		if (!viz[i])
			DFS(i);
}

void Graph::DFS(int x)
{
	int i;
	viz[x] = 1;
	for (i = 0; i < a[x].size(); i++)
		if (!viz[a[x][i]])
			DFS(a[x][i]);
	S.push(x);
}
void Graph::SortTop()
{
	int i;
	for (i = 1; i <= n; i++)
		if (!viz[i])
			DFS(i);
	while (!S.empty())
	{
		fout << S.top() << " ";
		S.pop();
	}
}


void Graph::DFS_T(int x,int ct)
{
	int i;
	viz_t[x] = 1;
	c[ct].push_back(x); //pt fiecare nod, din ce comp tconexa face parte
	for (i = 0; i < a_t[x].size(); i++)
		if (viz_t[a_t[x][i]] == 0)
			DFS_T(a_t[x][i], ct);
}

void Graph::CompTConexe()
{
	int i, j, x, ct = 0;
	while (!S.empty())
	{
		x = S.top();
		S.pop();
		if (viz_t[x] == 0)
		{
			ct++;
			DFS_T(x, ct);
		}

	}
	fout << ct << "\n";
	for (i = 1; i <= ct; i++)
	{
		for (j = 0; j < c[i].size(); j++)
			
				fout << c[i][j] << " ";
		fout << "\n";
	}

}


int main()
{
	int n, m;

	fin >> n >> m;
	Graph g(n, m);
	g.Citire_orientat();
	g.SortTop();









	return 0;
}