Pagini recente » Cod sursa (job #2720896) | Cod sursa (job #1449451) | Cod sursa (job #1948236) | Cod sursa (job #1607116) | Cod sursa (job #2419793)
#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");
}