【HDU 1548】【BFS】A strange lift

   其实重点是,输入的顺序是每个楼只能按的,而不是按顺序来,所以一开始总是想不对。


讲道理 最短路也是可以的,就交给你们了! 

#include "iostream"
#include "algorithm"
#include "queue"
using namespace std;
int a,b,n;
int vis[205],lift[205];
bool check(int x)
{
	if(x>=0 && x<=n && vis[x]==0)
		return true;
	return false;
}
int main(int argc, char const *argv[])
{
	while(~scanf("%d",&n),n)
	{
		queue<int> q;
		memset(vis,0,sizeof(vis));
		memset(lift,0,sizeof(lift));
		scanf("%d %d",&a,&b);
		for (int i = 1; i <= n; ++i)
			scanf("%d",&lift[i]);
		int flag=1;
		q.push(a);
		vis[a]=1;
		while(!q.empty())
		{
			int t1=q.front();
			q.pop();
			if(t1==b)
			{
				flag=1;
				break;
			}
			int t2=t1+lift[t1];
			//printf("%d\n",t2);
			if(check(t2))
			{
				vis[t2]=vis[t1]+1;
				q.push(t2);
				//printf("1\n");
			}
			t2=t1-lift[t1];
			//printf("%d\n",t2);
			if(check(t2))
			{
				vis[t2]=vis[t1]+1;
				q.push(t2);
				//printf("2\n");
			}
		}
		flag?printf("%d\n",vis[b]-1):printf("-1\n");
        
	}
	return 0;
}

你可能感兴趣的:(c,水题,bfs)