1. 程式人生 > >NOIP2014 Day2T2 尋找道路 bfs

NOIP2014 Day2T2 尋找道路 bfs

       實際上也是水題。。首先從終點沿反向邊將所有能到達終點的點求出來。然後列舉每個點看是否符合題目中的第一條條件。然後沿著所有滿足條件的點找出最短路就行了。

把一個sta達成1WA了一發。。真是沒救了:

#include<iostream>
#include<cstdio>
#include<cstring>
#define N 400005
using namespace std;

int n,m,sta,gol,tot,fst[N],pnt[N],nxt[N],len[N];
int d[N],h[N]; bool vis[N],ok[N];
void add(int aa,int bb,int cc){
	pnt[++tot]=bb; len[tot]=cc; nxt[tot]=fst[aa]; fst[aa]=tot;
}
int main(){
	scanf("%d%d",&n,&m); int i;
	for (i=1; i<=m; i++){
		int x,y; scanf("%d%d",&x,&y);
		add(x,y,1); add(y,x,0);
	}
	scanf("%d%d",&sta,&gol);
	int head=0,tail=1; vis[gol]=1; h[1]=gol;
	while (head<tail){
		int x=h[++head],p;
		for (p=fst[x]; p; p=nxt[p]) if (!len[p]){
			int y=pnt[p];
			if (!vis[y]){ vis[y]=1; h[++tail]=y; }
		}
	}
	for (i=1; i<=n; i++){
		ok[i]=1; int p;
		for (p=fst[i]; p; p=nxt[p])
			if (len[p] && !vis[pnt[p]]){ ok[i]=0; break; }
	}
	memset(d,-1,sizeof(d)); d[sta]=0;
	head=0; tail=1; h[1]=sta;
	while (head<tail){
		int x=h[++head],p;
		for (p=fst[x]; p; p=nxt[p]) if (len[p]){
			int y=pnt[p]; if (!ok[y]) continue;
			if (d[y]==-1){
				d[y]=d[x]+1; h[++tail]=y;
			}
		}
	}
	printf("%d\n",d[gol]);
	return 0;
}

by lych

2015.12.22