A strange lift
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 94 Accepted Submission(s) : 49
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem Description
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 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
Sample Input
5 1 5 3 3 1 2 5 0
Sample Output
3
很典型的单源最短路径题目,输入的时候把第i层的电梯能到的点判断在不在范围内就行了。代码是迪杰斯特拉算法。
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int map[211][211];
int dis[211];
int jl[211];
void d(int n,int st ){
int i,j,k,s;
jl[st]=1;
for(i=1;i<=n;i++)
dis[i]=map[st][i];
dis[st]=0;
for(i=1;i<=n-1;i++)
{
int min=-1;
for(j=1;j<=n;j++){
if(jl[j]==0&&dis[j]!=-1&&(min==-1||min>dis[j]))
{
min=dis[j];
s=j;
}
}
if(min==-1){
break;
}
jl[s]=1;
for(j=1;j<=n;j++)
{
if(map[s][j]!=-1&&dis[s]!=-1&&(dis[j]==-1||dis[s]+map[s][j]<dis[j]))
dis[j]=map[s][j]+dis[s];
}
}
}
int main(){
int n,a,b;
while(scanf("%d",&n),n){
scanf("%d%d",&a,&b);
memset(map,-1,sizeof(map));
memset(dis,-1,sizeof(dis));
memset(jl,0,sizeof(jl));
int i,j,k;
for(i=1;i<=n;i++)
map[i][i]=0;
for(i=1;i<=n;i++){
int aa;
scanf("%d",&aa);
if(aa==0)continue;
if(i-aa>=1)map[i][i-aa]=1;
if(i+aa<=n)map[i][i+aa]=1;
}
d(n,a);
if(a==b){
cout<<"0"<<endl;
}
else {
if(dis[b]!=-1)cout<<dis[b]<<endl;
else cout<<"-1"<<endl;
}
}
return 0;
}