Cod sursa(job #2419793)

Utilizator mihai.badilaBadila Mihai mihai.badila Data 9 mai 2019 13:40:10
Problema Sortare topologica Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <list>
#include <stack>

using namespace std;

class graph
{
	int n;

	list<int> *adj;

	void TopologicalSortUtil(int v, bool visited[], stack<int> &stack);
public:
	graph(const char* file);

	void addEdge(int v, int w);

	void TpS(const char* file);
};

graph::graph(const char* file)
{
	this->n = 0;
	ifstream f(file);

	this->adj = new list<int>[100];

	while (!f.eof())
	{
		int a, b;
		f >> a >> b;
		addEdge(a, b);
		this->n++;
	}
	f.close();
}

void graph::addEdge(int v, int w)
{
	adj[v].push_back(w);
}
void graph::TopologicalSortUtil(int v, bool visited[], stack<int> &stack)
{
	visited[v] = true;

	list<int>::iterator it;
	for (it = adj[v].begin(); it != adj[v].end(); ++it)
		if (visited[*it] == false)
			TopologicalSortUtil(*it, visited, stack);

	stack.push(v);
}

void graph::TpS(const char* file)
{
	stack<int> Stack;

	bool *visited = new bool[n];

	for (int i = 1; i <= n; i++)
		visited[i] = false;

	for (int i = 1; i <= n; i++)
		if (visited[i] == false)
			TopologicalSortUtil(i, visited, Stack);

	ofstream g(file);
	while (!Stack.empty())
	{
		g << Stack.top() << " ";
		Stack.pop();
	}
	g.close();
}

int main()
{
	graph g("sortaret.in");
	g.TpS("sortaret.out");
}