Noip 2014 Finding the Way --- Shortest Path + Search

Problem Solution: This topic mainly examines the shortest path + search
A directed graph with 1 edges, a given starting point and an end point, and a shortest path from beginning to end.
1. search: there will be points that are not connected to the end of the subject. They will be deleted and the dots connected to them will traverse the markup on the graph. (Note: The first tag cannot be removed directly, and the second tag deletion may have a post-validity.)
2. Shortest Path: Skip the Unmarked Point and Run the Shortest Path
The code is as follows:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<queue>
using namespace std;
struct E
{
	int start,to;
}e[389574];
int d[389574],h[982341];
bool v[346237],flag[923245];
int n,m,p,x,y,a,b,P=0;
void add(int start,int to)
{
	e[++P].start=h[start];
	e[P].to=to;
	h[start]=P;
}
void spfa(int p)
{
	memset(v,0,sizeof(v));
	memset(d,9999999,sizeof(d));
	queue<int> q;
	q.push(p);
	v[p]=1;d[p]=0;
	while(!q.empty())
	{
		int k=q.front();
		q.pop();v[k]=0;
		for(int i=h[k];i;i=e[i].start)
		{
			int t=e[i].to;
			if(d[t]>d[k]+1&&flag[t])
			{
				d[t]=d[k]+1;
				if(!v[t]){v[t]=1;q.push(t);}
			}
		}
	}
}
void bfs(int p)
{
	queue<int> q;
	memset(v,0,sizeof(v));
	q.push(p);
	flag[p]=v[p]=1;
	while(!q.empty())
	{
		int k=q.front();q.pop();
		for(int i=h[k];i;i=e[i].start)
		{
			int t=e[i].to;
			if(!v[t])
			{
				v[t]=flag[t]=1;
				q.push(t);
			}
		}
	}
}
int main()
{
	cin>>n>>m;
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y;
		add(y,x);
	}
	cin>>a>>b;
	bfs(b);
	for(int i=1;i<=n;i++)v[i]=flag[i];
	for(int i=1;i<=n;i++)
	{
		if(!v[i])
			for(int j=h[i];j;j=e[j].start)
			{
				int k=e[j].to;
				if(flag[k])flag[k]=0;
			}
	}
	spfa(b);
	if(d[a]<=999999)cout<<d[a]<<endl;
	else cout<<"-1"<<endl;
	return 0;
}

Posted by connex on Tue, 01 Oct 2019 01:31:39 -0700