Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 19516 Accepted Submission(s): 7224
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"?
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.
#include <stdio.h> #include <algorithm> #include <string.h> #include <math.h> #include <queue> using namespace std; const int N =205; const int INF = 9999999; int n; int graph[N][N]; int low[N]; bool vis[N]; void dijkstra(int s){ memset(vis,false,sizeof(vis)); for(int i=1;i<=n;i++){ low[i] = graph[s][i]; } vis[s] = true; for(int i=1;i<n;i++){ int Min = INF; for(int j=1;j<=n;j++){ if(Min>low[j]&&!vis[j]){ s = j; Min = low[j]; } } vis[s] = true; for(int j=1;j<=n;j++){ if(low[j]>low[s]+graph[s][j]&&!vis[j]){ low[j] = low[s]+graph[s][j]; } } } } int main() { while(scanf("%d",&n)!=EOF,n){ int s,t; scanf("%d%d",&s,&t); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(i==j) graph[i][j]=0; else graph[i][j] = INF; } } for(int i=1;i<=n;i++){ int num; scanf("%d",&num); if(i-num>=1) graph[i][i-num] = 1; if(i+num<=n) graph[i][i+num] = 1; } dijkstra(s); if(low[t]>=INF) printf("-1\n"); else printf("%d\n",low[t]); } return 0; }