Luogu P3916 图的遍历

题目描述

给出NN个点,MM条边的有向图,对于每个点vv,求A(v)A(v)表示从点vv出发,能到达的编号最大的点。

输入输出格式

输入格式:

第1 行,2 个整数N,MN,M。

接下来MM行,每行2个整数U_i,V_iUi​,Vi​,表示边(U_i,V_i)(Ui​,Vi​)。点用1, 2,\cdots,N1,2,⋯,N编号。

输出格式:

N 个整数A(1),A(2),\cdots,A(N)A(1),A(2),⋯,A(N)。

输入输出样例

输入样例#1: 复制

4 3
1 2
2 4
4 3

输出样例#1: 复制

4 4 3 4

说明

• 对于60% 的数据,1 \le N . K \le 10^31≤N.K≤103;

• 对于100% 的数据,1 \le N , M \le 10^51≤N,M≤105。

反向建边从大到小跑dfs

#include<cstdio>
#include<iostream>
using namespace std;
int read()
{
	int ret=0; char ch=getchar();
	while(ch<'0'||ch>'9') ch=getchar();
	while(ch>='0'&&ch<='9')
		ret=(ret<<1)+(ret<<3)+ch-'0',ch=getchar();
	return ret;
}

const int N=1e6+5;
int n,m,f[N];
bool fl[N];
int cnt,he[N],to[N],nxt[N];

inline void add(int u,int v)
{
	to[++cnt]=v,nxt[cnt]=he[u],he[u]=cnt;
}

void dfs(int u,int k)
{
	f[u]=k;
	for(int e=he[u];e;e=nxt[e])
	{
		int v=to[e];
		if(!f[v]) dfs(v,k);
	}
}
int main()
{
	n=read(),m=read();
	for(int i=1;i<=m;i++)
	{
		int u=read(),v=read();
		add(v,u);
	}
	for(int i=n;i;i--)
		if(!f[i]) dfs(i,i);
	for(int i=1;i<n;i++)
		printf("%d ",f[i]);
	printf("%d\n",f[n]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/YYHS_WSF/article/details/83272938
今日推荐