https://www.luogu.com.cn/problem/P5318
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
const int MAXN = 100005;
int n, m;
vector<int>p[MAXN];
vector<int>k[MAXN];
queue<int>q;
bool u[MAXN];
bool w[MAXN];
void solve(int x) {
cout << x << " ";
for (int i = 0, sz = k[x].size(); i < sz; i++) {
if (!w[p[x][i]]) {
w[p[x][i]] = true;
solve(k[x][i]);
}
}
}
int main() {
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int x, y;
cin >> x >> y;
p[x].push_back(y);
k[x].push_back(y);
}
w[1] = true;
u[1] = true;
q.push(1);
solve(1);
cout << endl;
while (!q.empty()) {
int x = q.front();
q.pop();
cout << x << " ";
for (int i = 0, sz = p[x].size(); i < sz; i++) {
if (!u[p[x][i]]) {
u[p[x][i]] = true;
q.push(p[x][i]);
}
}
}
return 0;
}