Files
python/TangDou/LuoGuBook/P3916_2.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

51 lines
1.4 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n; //n个结点
int m; //m条边
int res[N];
int u, v;
vector<int> p[N]; //vector存图
//此代码过了9个测试点1个测试点TLE!
//为啥会TLE呢看一下数据范围1≤N,M≤10^5,遍历每个结点是N
// 假设第一个结点就有M条边那么它需要执行M次
// 所有节点遍历一遍历就是N*M次时间复杂度就是1e10啊一秒肯定过不了啊
bool st[N];
/**
* 深度优先搜索
* @param x 从哪个号结点出发
* @param ne 到达了哪个结点
*/
void dfs(int x, int ne) {
if (!st[ne]) {
st[ne] = true;
//没走过更新最大号为d
res[x] = max(ne, res[x]);
//遍历所有出边,尝试找到更大号的结点
for (int i = 0; i < p[ne].size(); i++) dfs(x, p[ne][i]);
}
}
int main() {
//读入
scanf("%d%d", &n, &m);
//构建图
for (int i = 1; i <= m; i++) {
scanf("%d%d", &u, &v);
p[u].push_back(v); //正向建边,结点u出发有一条到结点v的边
}
//逐个深度优先搜索,找出每个结点能够到达的最大号结点
for (int i = 1; i <= n; i++) {
memset(st, false, sizeof st);
dfs(i, i);
}
//输出
for (int i = 1; i <= n; i++) printf("%d ", res[i]);
printf("\n");
return 0;
}