Question E: Strange elevator time limit: 1 Sec memory limit: up to MB
Submitted by: Resolution: 16
Submitted State [Discussion Version] Title Description
One day Tong Tong made a dream, dreamed of a very strange elevator. Elevators can be parked on each floor of the building, and there is a number k on the first floor (1≤i≤n); (0≤ki≤n). Elevators have only four buttons: on, off, up, down. The number of layers above and below equals that number on the current floor. Of course, if the requirements are not met, the corresponding buttons will fail. For example: 3 3 1 2 5 represents Ki (K1=3,k2=3, ...), starting from the first floor. On the first floor, press "up," can go to the 4 floor, press "down" is not working because there is no-2 floor. So, how many buttons do I have to press a few times from floor A to floor B?
Input
1th Act three positive integers, indicating n,a,b (1≤n≤200,1≤a,b≤n);
The 2nd behavior n a positive integer that represents Ki.
Output
1 lines, that is, the minimum number of keystrokes, if not reachable, then output-1.
Sample input
5 1 53 3 1 2 5
Sample output
3
Try Dijkstra First, I found it, the code is as follows
#include <stdio.h>#include<string.h>#include<algorithm>using namespacestd;Const intINF =1<< -; intN;intmap[205][205];inta[205],cnt;intvis[205],cast[205]; voidDijkstra (intSinte) { intI,j,min,pos; memset (Vis,0,sizeof(VIS)); for(i =0; i<n; i++) Cast[i]=Map[s][i]; Cast[s]=0; Vis[s]=1; for(i =1; i<n; i++) {min=inf; for(j =0; j<n; J + +) { if(Cast[j]<min &&!)Vis[j]) {POS=J; Min=Cast[j]; } } if(min = =inf) Break; Vis[pos]=1; for(j =0; j<n; J + +) { if(Cast[pos]+map[pos][j]<cast[j] &&!Vis[j]) cast[j]= cast[pos]+Map[pos][j]; } }} intMain () {intI,j,s,e,x,y; scanf ("%d",&N); scanf ("%d%d",&s,&e); S--, e--; for(i =0; i<n; i++) for(j =0; j<n; J + +) Map[i][j]=inf; for(i =0; i<n; i++) {scanf ("%d",&A[i]); if(i+a[i]<N) map[i][i+a[i]] =1; if(i-a[i]>=0) Map[i][i-a[i]] =1; } Dijkstra (S,e); printf ("%d\n", cast[e]==inf?-1: Cast[e]); return 0;}View Code
Later with the BFS to pay a pitch, also past.
#include <iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<cmath>#include<map>#include<queue>#definell Long Long#defineRep (I,m,n) for (i=m;i<=n;i++)#defineINF 0x3f3f3f3fConst intmaxn=1e3+Ten;using namespacestd;intn,m,a,b;Const intdis[][2]={0,1,1,0,-1,0,0,-1};intQ[MAXN],VIS[MAXN];intMain () {inti,j,k,t; Queue<int>p; scanf ("%d%d%d",&n,&a,&b); Vis[a]=1; for(i=1; i<=n;i++) scanf ("%d",&Q[i]); P.push (a); while(!Q.empty ()) { intNow=p.front (), l=now-q[now],r=now+Q[now]; P.pop (); if(l>=1&&!vis[l]) P.push (l), vis[l]=vis[now]+1; if(R<=n&&!vis[r]) P.push (R), vis[r]=vis[now]+1; if(l==b| | R==B) Break; } printf ("%d\n", vis[b]-1); //System ("pause"); return 0;}View Code
Strange Elevator (HDU1548) (Dijkstra) or (BFS)