题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1548
题面:
A strange lift
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 16612 Accepted Submission(s): 6213
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
Sample Output
题目大意:
每层电梯对应一个值,可以有两种操作UP,DOWN,UP操作是该楼层层数+该层的Ki值,如果没超过N(楼高)就可以到达该层,同理,向下,i-ki,没小于1.就可以向下到达i-ki层,刚接触这种题目,比较难想到用最短路去求,做过了,就很自然可以想到最短路了。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#define inf 0x3f3f3f3f
using namespace std;
int mapp[210][210],dist[210];
bool vis[210];
void init()
{
for(int i=1;i<210;i++)
for(int j=1;j<210;j++)
{
if(i==j)
mapp[i][i]=0;
else
mapp[i][j]=inf;
}
for(int i=1;i<210;i++)
dist[i]=inf;
memset(vis,0,sizeof(vis));
}
void dijkstra(int s,int n)
{
int minn=inf,p=0,tmp;
for(int i=1;i<=n;i++)
{
if((i!=s)&&mapp[s][i]<minn)
{
minn=mapp[s][i];
p=i;
}
}
if(minn==inf)return;
dist[p]=minn;
while(1)
{
vis[p]=1;
for(int i=1;i<=n;i++)
{
tmp=dist[p]+mapp[p][i];
if(tmp<dist[i])
dist[i]=tmp;
}
minn=inf;
for(int i=1;i<=n;i++)
{
if(!vis[i]&&dist[i]<minn)
{
minn=dist[i];
p=i;
}
}
if(minn==inf)
break;
}
}
int main()
{
int n,a,b,k;
while(scanf("%d",&n))
{
if(n==0)break;
init();
scanf("%d%d",&a,&b);
for(int i=1;i<=n;i++)
{
scanf("%d",&k);
if(k+i<=n&&(k+i>0))
mapp[i][k+i]=1;
if((i-k)>0&&(i-k)<=n)
mapp[i][i-k]=1;
}
for(int i=1;i<=n;i++)
dist[i]=mapp[a][i];
dijkstra(a,n);
if(dist[b]==inf)
printf("-1\n");
else
printf("%d\n",dist[b]);
}
return 0;
}