题目直达 ----》 图的遍历
这个题主要是采用反向存图的操作;
然后使用DFS
进行遍历整个图即可
如果当前图已经遍历过了就return
否则就继续遍历
将答案存入数组res
中就可以了
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 100010;
vector<int>map[N];
int n, m;
int res[N];
void dfs(int x, int c)
{
if(res[x])return;
res[x] = c;
for (int i = 0; i < map[x].size(); ++i)
dfs(map[x][i], c);
//printf("%d ",c);
}
int main()
{
cin.tie(nullptr), cout.tie(NULL);
cin >> n >> m;
for (int i = 1; i <= m; ++i)
{
int a, b;
scanf("%d%d",&a, &b);//注意这里是反向存的图
map[b].push_back(a);
}
for (int i = n; i; --i) dfs(i, i);
for (int i = 1; i <= n; ++i) cout << res[i] << ' ';
return 0;
}