You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

51 lines
1.4 KiB

2 years ago
#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;
}