题目传送门
题意: 给你一张有向图,假设A(x)表示从x出发能到达的最大的点,输出A(1~n) 。
思路: 我们不妨反向建边,从x出发到的最大的点,就转换成从大点能走到哪些点,反向建边之后依次从大的点遍历,每次成功走到一些点就把点打标记避免重复询问同一个点导致答案错误。
#include<bits/stdc++.h>
#define endl '\n'
#define null NULL
#define ls p<<1
#define rs p<<1|1
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
#define int long long
#define pii pair<int,int>
#define ull unsigned long long
#define all(x) x.begin(),x.end()
#define IOS ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
#define ct cerr<<"Time elapsed:"<<1.0*clock()/CLOCKS_PER_SEC<<"s.\n";
char *fs,*ft,buf[1<<20];
#define gc() (fs==ft&&(ft=(fs=buf)+fread(buf,1,1<<20,stdin),fs==ft))?0:*fs++;
inline int read(){int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=gc();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=gc();}
return x*f;}
using namespace std;
const int N=1e5+5;
const int inf=0x3f3f3f3f;
const int mod=1e9+7;
const double eps=1e-7;
const double PI=acos(-1);
vector<int>e[N];int ans[N];
void bfs(int x)
{
ans[x]=x;
queue<int>q;
q.push(x);
while(!q.empty())
{
int t=q.front();q.pop();
for(auto i:e[t])
{
if(!ans[i])
{q.push(i);
ans[i]=x;}
}
}
}
signed main()
{
int n=read(),m=read();
while(m--)
{
int u=read(),v=read();
e[v].pb(u);
}
for(int i=n;i>=1;i--)
{
if(!ans[i])
{
bfs(i);
}
}
for(int i=1;i<=n;i++)
cout<<ans[i]<<' ';
}