Pagini recente » Cod sursa (job #2505896) | Cod sursa (job #2795242) | Rating Gyorfi Tamas (tamasgy) | Cod sursa (job #539126) | Cod sursa (job #2790722)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
class Graph {
private:
int n;
int m;
int start;
vector<vector<int>> adjList;
vector<int> dist;
queue<int> q;
bool vis[100001] = {false};
public:
Graph() {};
void directedGraph();
void undirectedGraph();
void directedGraphTopSort();
void bfs();
void dfs(int start);
void noConnComp();
void dfsTopSort(int start, stack <int>& topSorted);
void topSort();
};
void Graph :: directedGraph() {
ifstream fin("bfs.in");
fin >> n >> m >> start;
adjList.resize(n + 1);
for (int i = 0; i < m; i++) {
int x, y;
fin >> x >> y;
adjList[x].push_back(y);
}
fin.close();
}
void Graph :: undirectedGraph() {
ifstream fin("dfs.in");
fin >> n >> m;
adjList.resize(n + 1);
for (int i = 0; i < m; i++) {
int x, y;
fin >> x >> y;
adjList[x].push_back(y);
adjList[y].push_back(x);
}
fin.close();
}
void Graph :: directedGraphTopSort() {
ifstream fin("sortaret.in");
fin >> n >> m;
adjList.resize(n + 1);
for (int i = 0; i < m; i++) {
int x, y;
fin >> x >> y;
adjList[x].push_back(y);
}
fin.close();
}
void Graph :: bfs() {
ofstream fout("bfs.out");
q.push(start);
dist.resize(n + 1);
for (int i = 1; i <= n; i++)
dist[i] = -1;
dist[start] = 0;
while (!q.empty()) {
int nod = q.front();
q.pop();
for (auto i : adjList[nod])
if (dist[i] == -1) {
dist[i] = dist[nod] + 1;
q.push(i);
}
}
for (int i = 1; i <= n; i++)
fout << dist[i] << " ";
fout.close();
}
void Graph :: dfs(int start) {
vis[start] = true;
for (auto x : adjList[start])
if (!vis[x])
dfs(x);
}
void Graph :: noConnComp() {
ofstream fout("dfs.out");
int c = 0;
for (int i = 1; i <= n; i++)
if (!vis[i]) {
dfs(i);
c++;
}
fout << c;
fout.close();
}
void Graph :: dfsTopSort(int start, stack<int>& topSorted) {
vis[start] = true;
for (auto x : adjList[start])
if (!vis[x])
dfsTopSort(x, topSorted);
topSorted.push(start);
}
void Graph :: topSort() {
ofstream fout("sortaret.out");
stack<int> topSorted;
for (int i = 1; i <= n; i++)
if (!vis[i])
dfsTopSort(i, topSorted);
while (!topSorted.empty()){
fout << topSorted.top() << " ";
topSorted.pop();
}
fout.close();
}
int main()
{
Graph X;
X.directedGraphTopSort();
X.topSort();
return 0;
}