Problem Description
There is a strange lift.Thelift 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 youat floor i,if you press the button
"UP" , you will go up Kifloor,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 thfloor. Of course, the lift can't go up high than N,and can't go down lower than1. 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 thfloor,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 floorB,how many times at least he has to press the button "UP" or"DOWN"?
Input
The input consists of severaltest cases.,Each test case contains two lines.
The first line contains three integers N ,A,B( 1 <= N,A,B <= 200) whichdescribe 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 inputoutput a interger, the least times you have to press the button when you onfloor A,and you want to go to floor B.If you can't reach floor B,printf"-1".
Sample Input
5 1 5
3 3 1 2 5
0
Sample Output
3
題目簡介:一個很奇怪的電梯。第i層樓只能上ki層或者下ki層。i+ki不能超過頂樓或者i-ki不能到達負樓。問從A層到B層,需要按多少次,如果不能到達輸出-1。
方法:最短路。Dijkstra。可以把能到達的樓層之間看作是連通的且距離為1。
#include<stdio.h>#include<stdlib.h>#include<string.h>#define INF 1000000int n, a, b, k[210], dis[210][210], p[210];//dijkstravoid dijk(){int i, j,x, y, max, count = 0;memset(k,0,sizeof(k));//初始化for(i = 1;i<=n;i++){p[i] = dis[a][i];}p[a] = 1;for(i = 1;i<n;i++){max = INF;for(j = 1;j<=n;j++){if(!k[j]&&p[j]<max){max = p[j];x = j;}}if(max==INF)break;k[x] = 1;if(k[b])break;for(j = 1;j<=n;j++){if(!k[j]&&p[j] > p[x] + dis[x][j]){p[j] = p[x] + dis[x][j];}}} if(!k[b]||p[b]==INF){printf("-1\n");}else{printf("%d\n",p[b]);}};int main(){int m, i, j, c;while(scanf("%d",&n)!=EOF,n)//樓層數{scanf("%d%d",&a, &b);//起點和終點for(i = 1;i<=n;i++){for(j = 1;j<=n;j++){dis[i][j] = INF;}}//初始化距離for(i = 1;i<=n;i++){scanf("%d",&c);//每層樓可以升降的層數if(c==0)continue;if(i + c<=n){dis[i][i + c] = 1;//權數為1}if(i - c>0){dis[i][i - c] = 1;//權數為1}}if(a==b){printf("0\n");continue;}if(a<1||b<1||a>n||b>n){printf("-1\n");continue;}dijk();}system("pause");return 0;}