版权声明:while (!success) try(); https://blog.csdn.net/qq_35850147/article/details/89278942
题目描述
给出N个点,M条边的有向图,对于每个点v,求A(v)表示从点v出发,能到达的编号最大的点。
输入输出格式
输入格式:
第1 行,2 个整数N,M。
接下来M行,每行2个整数Ui,Vi,表示边(Ui,Vi)。点用1,2,⋯,N编号。
输出格式:
N 个整数A(1),A(2),⋯,A(N)。
输入输出样例
输入样例#1: 复制
4 3
1 2
2 4
4 3
输出样例#1: 复制
4 4 3 4
说明
• 对于60% 的数据,1≤N,M≤10^3;
• 对于100% 的数据,1≤N,M≤10^5。
题解
#include <bits/stdc++.h>
using namespace std;
int n, m, ans[100001];
vector<int> v[100001];
bool vis[100001];
void BFS(int x)
{
queue<int> q;
q.push(x);
while (!q.empty())
{
int t = q.front();
vis[t] = true;
q.pop();
ans[t] = max(ans[t], x);
for (int i = 0; i < v[t].size(); i++)
if (!vis[v[t][i]])
q.push(v[t][i]);
}
}
int main()
{
scanf("%d%d", &n, &m);
while (m--)
{
int a, b;
scanf("%d%d", &a, &b);
v[b].push_back(a);
}
for (int i = 1; i <= n; i++)
ans[i] = i;
for (int i = n; i >= 1; i--)
BFS(i);
for (int i = 1; i <= n; i++)
printf("%d%c", ans[i], i == n ? '\n' : ' ');
return 0;
}