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
Here comes the problem: when you are on floor A,and you want to go to floor
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
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
Sample Input
5 1 5
3 3 1 2 5
0
Sample Output
3
Recommend
8600
题目大意
一幢大楼有 n 层,有个电梯,第
求至少按几次电梯,才能从 a 走到
多组数据以一个单独的0结束,无解输出-1
solution
按照题目中的描述建图,然后跑最短路就好了
n 很小,Floyd和dijkstra应该都可以,但我好长时间没写spfa了,于是就写的spfa…
因为边权都是1,bfs应该也可以.
code
#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
template<typename T>
void input(T &x) {
x=0; T a=1;
register char c=getchar();
for(;c<'0'||c>'9';c=getchar())
if(c=='-') a=-1;
for(;c>='0'&&c<='9';c=getchar())
x=x*10+c-'0';
x*=a;
return;
}
#define MAXN 210
#define MAXM 510
struct Edge {
int u,v,w,next;
Edge(int u=0,int v=0,int w=0,int next=0):
u(u),v(v),w(w),next(next) {}
};
Edge edge[MAXM];
int head[MAXN],cnt;
void addedge(int u,int v,int w) {
edge[++cnt]=Edge(u,v,w,head[u]);
head[u]=cnt;
return;
}
#define inf 2147483647
int n,m;
int dis[MAXN];
bool inq[MAXN];
queue<int> q;
int spfa(int s,int t) {
dis[s]=0;
q.push(s);
inq[s]=true;
while(!q.empty()) {
int u=q.front();
q.pop();
inq[u]=false;
for(int i=head[u];i;i=edge[i].next) {
int v=edge[i].v;
if(dis[u]+edge[i].w<dis[v]) {
dis[v]=dis[u]+edge[i].w;
if(!inq[v]) {
q.push(v);
inq[v]=true;
}
}
}
}
return dis[t];
}
int main() {
int A,B;
while(scanf("%d",&n)==1&&n!=0) {
for(int i=1;i<=n;i++)
dis[i]=inf,head[i]=0;
cnt=0;
input(A),input(B);
for(int i=1;i<=n;i++) {
int k;
input(k);
if(i-k>=1) addedge(i,i-k,1);
if(i+k<=n) addedge(i,i+k,1);
}
int ans=spfa(A,B);
if(ans==inf) ans=-1;
printf("%d\n",ans);
}
return 0;
}