1、P3916 图的遍历 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
#include<bits/stdc++.h>
using namespace std;
vector<int> a[100010];
int n,m;
int ans[100010];
void dfs(int s,int now)
{
ans[s] = now;
for (int& t : a[s])
{
if (!ans[t])dfs(t, now);
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y;
cin >> x >> y;
a[y].push_back(x);
}
for (int i = n; i > 0; i--)
{
if (!ans[i])dfs(i,i);
}
for (int i = 1; i < n; i++)
cout << ans[i] << ' ';
cout << ans[n] << endl;
return 0;
}