hdu 1548 A strange lift 宽搜bfs+优先队列
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1548
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"?
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"?
题意描述:n层楼(1<=n<=200),每层楼一个数字Ki和两个按钮UP和DOWN,如果你在A层楼,A层楼的数字Ka=3,你可以按下UP按钮到A+Ka层楼,按下DOWN按钮到A-Ka层楼(前提是A+Ka和A-Ka都在n的范围里)。 现在你在A层楼,要到目的地B层楼,问按下按钮的最少次数。
算法分析:直接bfs暴搜即可,由于涉及到最少次数问题,我习惯性的用到了优先队列处理。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cstdlib> 5 #include<cmath> 6 #include<algorithm> 7 #include<queue> 8 #define inf 0x7fffffff 9 using namespace std; 10 const int maxn=200+10; 11 const int M = 40000+10; 12 13 int n,A,B; 14 int an[maxn]; 15 struct node 16 { 17 int cnt,id; 18 int value; 19 friend bool operator < (node a,node b) 20 { 21 return a.cnt > b.cnt; 22 } 23 }cur,tail; 24 25 int vis[maxn]; 26 int bfs() 27 { 28 priority_queue<node> Q; 29 cur.id=A ;cur.cnt=0 ; 30 cur.value=an[A]; 31 Q.push(cur); 32 memset(vis,0,sizeof(vis)); 33 vis[A]=1; 34 int count=0; 35 while (!Q.empty()) 36 { 37 cur=Q.top() ;Q.pop() ; 38 if (cur.id==B) return cur.cnt; 39 40 //cout<<cur.id<<" "<<an[cur.id]<<" "<<cur.cnt<<endl; 41 tail.id=cur.id+an[cur.id]; 42 if (tail.id>=1 && tail.id<=n && !vis[tail.id]) 43 { 44 tail.value=an[tail.id]; 45 tail.cnt=cur.cnt+1; 46 vis[tail.id]=1; 47 Q.push(tail); 48 } 49 50 tail.id=cur.id-an[cur.id]; 51 if (tail.id>=1 && tail.id<=n && !vis[tail.id]) 52 { 53 tail.value=an[tail.id]; 54 tail.cnt=cur.cnt+1; 55 vis[tail.id]=1; 56 Q.push(tail); 57 } 58 } 59 return -1; 60 } 61 62 int main() 63 { 64 while (scanf("%d",&n)!=EOF && n) 65 { 66 scanf("%d%d",&A,&B); 67 for (int i=1 ;i<=n ;i++) scanf("%d",&an[i]); 68 printf("%d\n",bfs()); 69 } 70 return 0; 71 }