洛谷P3916 图的遍历
\(\large{题目链接}\)
\(\\\)
\(\Large\textbf{Solution: } \large{1.一种简单的思路:缩点 + dp,这里就不再赘述。\\2.介绍一种O(n + m)的优秀方法,考虑反向建边,然后从n点到1dfs,这样一旦第一次到达一点,那么当前的起点即为这个点的答案。}\)
\(\\\)
\(\Large\textbf{Code: }\)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 6;
int n, m, vis[N];
vector <int> v[N];
int read() {
int x = 0;
char ch = getchar();
while (!isdigit(ch)) ch = getchar();
while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
return x;
}
void dfs(int x, int Max) {
if (vis[x]) return;
vis[x] = Max;
for (int i = 0; i < v[x].size(); ++i) dfs(v[x][i], Max);
return;
}
int main() {
n = read(), m = read();
int x, y;
for (int i = 1; i <= m; ++i) x = read(), y = read(), v[y].push_back(x);
for (int i = n; i >= 0; --i) dfs(i, i);
for (int i = 1; i <= n; ++i) printf("%d ", vis[i]); puts("");
return 0;
}