#pragma GCC diagnostic ignored "-Wunused-parameter"
#define _USE_MATH_DEFINES
#include <bits/stdc++.h>
using namespace std;
#define INP "solve"
#define OUT "solve"
const long long INF_LL = 1e17;
const int INF = 1e9 + 100;
const int MOD = 1e9 + 7;
const int Base = 311;
const long double EPS = 1e-10;
const int BLOCK = 1000;
const int dx[4] = {0, 0, 1, -1};
const int dy[4] = {1, -1, 0, 0};
mt19937 rnd(chrono::system_clock::now().time_since_epoch().count());
void open_file() {
#ifdef THEMIS
freopen(INP ".inp","r",stdin);
freopen(OUT ".out","w",stdout);
#endif // THEMIS
}
const int maxN = 5e5 + 100;
int in_deg[maxN];
vector<int> adj[maxN];
int n, m;
//n = |V|, m = |E|
void readGraph() {
cin >> n >> m;
//n = |V|, m = |E|
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
adj[u].push_back(v);
in_deg[v]++;
}
for (int u = 0; u < n; u++) {
cout << "adj(" << u << "): ";
for (int v : adj[u]) {
cout << v << ' ';
}
cout << '\n';
}
cout << '\n';
}
int used[maxN]; //Kiểm tra đỉnh u đã thăm hay chưa ?
vector<int> T;
void topo_DFS(int u) {
used[u] = 1;
for (int v : adj[u]) {
if (used[v] == 0) {
topo_DFS(v);
}
}
T.push_back(u);
}
void topo_BFS() {
queue<int> Q;
for (int i = 0; i < n; i++) {
if (in_deg[i] == 0) {
Q.push(i);
}
}
assert((int)Q.size() > 0); ///Chắc chắn tồn tại đỉnh có bậc vào = 0
int idQ = 0;
while ((int)Q.size() != 0) {
{
///Dùng để in thử, các bạn không cần quan tâm phần này
vector<int> vertice;
while ((int)Q.size() != 0) {
int u = Q.front(); Q.pop();
vertice.push_back(u);
}
cout << "Queue " << idQ << ": " << '\n';
for (int u : vertice) {
cout << u << ' ';
Q.push(u);
}
cout << '\n';
idQ++;
}
int u = Q.front(); Q.pop();
T.push_back(u);
for (int v : adj[u]) {
--in_deg[v];
if (in_deg[v] == 0) {
Q.push(v);
}
}
}
}
void sol() {
readGraph();
{
for (int i = 0; i < n; i++) used[i] = 0;
T.clear();
for (int i = 0; i < n; i++) { //Có thể là một hoán vị của n
if (used[i] == 0) {
topo_DFS(i);
}
}
reverse(T.begin(), T.end());
cout << "Thu tu topo sort voi DFS: " << '\n';
for (int u : T) cout << u << ' ';
cout << '\n';
cout << '\n';
}
{
T.clear();
topo_BFS();
cout << "Thu tu topo sort voi BFS: " << '\n';
for (int u : T) cout << u << ' ';
cout << '\n';
}
}
void solve() {
int T;
//cin >> T;
T = 1;
int TestCase = 0;
while (T--) {
TestCase += 1;
//cout << "Case #" << TestCase << ":" << ' ';
///cout << "Case #" << TestCase << '\n';
//cout << "Test " << TestCase << ": ";
sol();
}
}
int main(int argc,char *argv[]) {
///srand(time(nullptr));
ios_base::sync_with_stdio(0); cin.tie(nullptr); cout.tie(nullptr);
open_file();
solve();
}