Pagini recente » Cod sursa (job #2310480) | Cod sursa (job #1854685) | Cod sursa (job #712142) | Cod sursa (job #2309928) | Cod sursa (job #1815925)
// Kahn's algorithm for topologically sorting a DAG
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <functional>
using namespace std;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3f;
template<typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; }
template<typename T, typename U> static void amax(T &x, U y) { if (y > x) x = y; }
struct Node {
bool visited;
int deg; // number of incoming edges
vector<int> adj;
Node() {
visited = false;
deg = 0;
}
};
int N, M;
Node V[100005];
vector<int> top;
vector<int> s; // set holding the current nodes with no incoming edges;
int main() {
freopen("sortaret.in", "r", stdin);
freopen("sortaret.out", "w", stdout);
cin >> N >> M;
for (int i = 0; i < M; i++) {
int x, y; cin >> x >> y;
V[x].adj.push_back(y);
V[y].deg++;
}
// construct S
for (int i = 1; i <= N; i++) {
if (V[i].deg == 0) s.push_back(i);
}
while (!s.empty()) {
int node = s.back();
top.push_back(node);
s.pop_back();
for (auto &i : V[node].adj) {
int current = V[node].adj[0];
V[current].deg--;
V[node].adj.erase(V[node].adj.begin());
if (V[current].deg <= 0) {
s.push_back(current);
}
}
}
for (auto &i : top) {
cout << i << " ";
}
cout << endl;
}