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"?
 
题意描述: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暴搜即可,由于涉及到最少次数问题,我习惯性的用到了优先队列处理。
 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<algorithm>
#include<queue>
#define inf 0x7fffffff
using namespace std;
const int maxn=+;
const int M = +; int n,A,B;
int an[maxn];
struct node
{
int cnt,id;
int value;
friend bool operator < (node a,node b)
{
return a.cnt > b.cnt;
}
}cur,tail; int vis[maxn];
int bfs()
{
priority_queue<node> Q;
cur.id=A ;cur.cnt= ;
cur.value=an[A];
Q.push(cur);
memset(vis,,sizeof(vis));
vis[A]=;
int count=;
while (!Q.empty())
{
cur=Q.top() ;Q.pop() ;
if (cur.id==B) return cur.cnt; //cout<<cur.id<<" "<<an[cur.id]<<" "<<cur.cnt<<endl;
tail.id=cur.id+an[cur.id];
if (tail.id>= && tail.id<=n && !vis[tail.id])
{
tail.value=an[tail.id];
tail.cnt=cur.cnt+;
vis[tail.id]=;
Q.push(tail);
} tail.id=cur.id-an[cur.id];
if (tail.id>= && tail.id<=n && !vis[tail.id])
{
tail.value=an[tail.id];
tail.cnt=cur.cnt+;
vis[tail.id]=;
Q.push(tail);
}
}
return -;
} int main()
{
while (scanf("%d",&n)!=EOF && n)
{
scanf("%d%d",&A,&B);
for (int i= ;i<=n ;i++) scanf("%d",&an[i]);
printf("%d\n",bfs());
}
return ;
}
上一篇:php中文乱码问题分析及解决办法


下一篇:RSA 非对称加密原理