HDU 1548 BFS

发布时间:2017-4-24 7:43:59 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"HDU 1548 BFS",主要涉及到HDU 1548 BFS方面的内容,对于HDU 1548 BFS感兴趣的同学可以参考一下。

A strange lift Problem Description There is a strange lift.The lift can stop can at every floor as you want, and there is a number Ki(0 <= Ki <= N) on every floor.The lift have just two buttons: up and down.When you at floor i,if you press the button "UP" , you will go up Ki floor,i.e,you will go to the i+Ki th floor,as the same, if you press the button "DOWN" , you will go down Ki floor,i.e,you will go to the i-Ki th floor. Of course, the lift can't go up high than N,and can't go down lower than 1. For example, there is a buliding with 5 floors, and k1 = 3, k2 = 3,k3 = 1,k4 = 2, k5 = 5.Begining from the 1 st floor,you can press the button "UP", and you'll go up to the 4 th floor,and if you press the button "DOWN", the lift can't do it, because it can't go down to the -2 th floor,as you know ,the -2 th floor isn't exist. Here comes the problem: when you are on floor A,and you want to go to floor B,how many times at least he has to press the button "UP" or "DOWN"?   Input The input consists of several test cases.,Each test case contains two lines. The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) which describe above,The second line consist N integers k1,k2,....kn. A single 0 indicate the end of the input.   Output For each case of the input output a interger, the least times you have to press the button when you on floor A,and you want to go to floor B.If you can't reach floor B,printf "-1".   Sample Input 5 1 5 3 3 1 2 5 0   Sample Output 3 bfs 不过后来看网上很多都是用最短路径来解决的.... #include <iostream> #include <algorithm> #include <stdio.h> #include <string> #include <cmath> #include <queue> #include <cstdlib> using namespace std; int vis[201]; int next[201]; int n; int a[201]; int bfs(int s,int e) { queue<int> q; q.push(s); vis[s]=1; a[s]=0; while(!q.empty()) { int t=q.front(); q.pop(); if(t==e)return 1; int m=t-next[t]; if(m>=0&&!vis[m]) { a[m]=a[t]+1; vis[m]=1; q.push(m); } int w=t+next[t]; if(w<n&&!vis[w]) { a[w]=a[t]+1; vis[w]=1; q.push(w); } } return 0; } int main() { int i,j,s,e; while(scanf("%d",&n),n) { memset(next,0,sizeof(next)); memset(a,0,sizeof(a)); memset(vis,0,sizeof(vis)); scanf("%d%d",&s,&e); for(i=0;i<n;i++) scanf("%d",&next[i]); s--,e--; int x=bfs(s,e); if(x!=0) printf("%d\n",a[e]); else puts("-1"); } return 0; }  

上一篇:【俘获&&云朵xp主题】_8.21
下一篇:Android中dip(dp)与px之间单位转换

相关文章

关键词: HDU 1548 BFS

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款