【题解】洛谷P2296 寻找道路(最短路 bfs)

这道题理论上用bfs是可以解决的,但要判断的条件比较多。看到数据范围后,我决定还是用最短路来解决更加方便。

思路就是我们要处理出不能用的点,然后跑最短路时判断如果出现这个点跳过就好了。

判断不能用的点,我们可以从终点开始扩散,将到达的每一个点打上标记。这样我们就可以初步找出从起点出发进入某个点是死胡同的情况。处理出这些点后,我们再从起点出发,对每一个打过标记的点进行操作,如果打过标记的点扩展出去第一层的点没有标记,证明这个点不能用,从它出发的路有不能到达终点的情况,然后在全新的数组里记录能否使用。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
using namespace std;
const int maxn=10010;
const int maxm=200100;
int n,m,ex,ey,s=0,t=0,l;
int head[maxn],nnext[maxm*2],to[maxm*2],team[maxm*8];
int head1[maxn],nnext1[maxm*2],to1[maxm*2];
int team1[maxn*8];
int tot,tot1;
int dis[maxn];
bool b[maxn];
bool w[maxn];
bool pd[maxn];
void add(int x,int y)
{
	tot++;
	nnext[tot]=head[y];
	head[y]=tot;
	to[tot]=x;
	tot1++;
	nnext1[tot1]=head1[x];
	head1[x]=tot1;
	to1[tot1]=y;
}
void dfs(int x)
{
	w[x]=true;
	for(int i=head[x];i;i=nnext[i])
	{
		int y=to[i];
		if(!w[y])
		{
			dfs(y);
		}
	}
}
int main()
{
//	freopen("road.in","r",stdin);
//	freopen("road.out","w",stdout);
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		if(x==y) continue;
		add(x,y);
	}
	scanf("%d%d",&ex,&ey);
	dfs(ey);
	for(int i=1;i<=n;i++)
	{
		if(w[i]==false) continue;
		bool flag=false;
		for(int j=head1[i];j;j=nnext1[j])
		{
			int y=to1[j];
			if(!w[y]) flag=true;
		}
		if(!flag) b[i]=true;
	}

	
	for(int i=1;i<=n;i++)
	{
		dis[i]=1e9;
	}dis[ey]=0;
	
	team[t]=ey;
	t++;
	pd[ey]=true;

	while(s!=t)
	{
		int now=team[s];
		s++;
		pd[now]=false;
		for(int i=head[now];i;i=nnext[i])
		{
			int y=to[i];
			if(b[y]==false) continue;
			if(dis[y]>dis[now]+1)
			{
				dis[y]=dis[now]+1;
				if(pd[y]==false)
				{
					team[t]=y;
					t++;
					pd[y]=true;				
				}
			}
		}
	}
	
	if(dis[ex]!=1e9) printf("%d",dis[ex]);
	else printf("-1");
	
	fclose(stdin);
	fclose(stdout);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Rem_Inory/article/details/81609715