Pagini recente » Cod sursa (job #384873) | Cod sursa (job #3182654) | Cod sursa (job #2939608) | Cod sursa (job #2551734) | Cod sursa (job #760204)
Cod sursa(job #760204)
#include <fstream>
#include <vector>
class Graph {
public:
Graph(); // Constructor
~Graph(); // Destructor
void read(const char* file); // Read the graph from the input file.
void topsort(); // Sort the graph by topological sort.
void write(const char* file); // Write the list of sorted nodes.
private:
int N; // No of nodes
int M; // No of edges
std::vector<int> nodes; // The list of topological sorted nodes
std::vector<int>* adj; // adj[i] is the list of neighbours of node i
void dfs(int s, bool* visited); // DFS from source s.
};
int main()
{
Graph G;
G.read("sortaret.in");
G.topsort();
G.write("sortaret.out");
return 0;
}
Graph :: Graph()
{
adj = NULL;
}
Graph :: ~Graph()
{
delete [] adj;
}
void Graph :: read(const char* file)
{
std::ifstream fin;
int i, j;
fin.open(file);
fin >> N >> M;
adj = new std::vector<int> [N + 1];
while (fin >> i >> j) {
adj[i].push_back(j);
}
fin.close();
}
void Graph :: dfs(int s, bool* visited)
{
int i;
for (i = 0; i < (int) adj[s].size(); i++) {
if (!visited[adj[s][i]]) {
visited[adj[s][i]] = true;
dfs(adj[s][i], visited);
}
}
nodes.push_back(s);
}
void Graph :: topsort()
{
bool* visited;
int i;
visited = new bool [N + 1];
for (i = 1; i <= N; i++) {
visited[i] = false;
}
for (i = 1; i <= N; i++) {
if (!visited[i]) {
visited[i] = true;
dfs(i, visited);
}
}
delete [] visited;
}
void Graph :: write(const char* file)
{
std::ofstream fout;
int i;
fout.open(file);
for (i = nodes.size() - 1; i >= 0; i--) {
fout << nodes[i] << ' ';
}
fout.close();
}