洛谷 P1135 【奇怪的电梯】
- 题库 :洛谷
- 题号 :1135
- 题目 :奇怪的电梯
- link :https://www.luogu.org/problemnew/show/P1135
一. 动态规划 :
- 思路 :这道题用动规来解决其实很简单,f[i][j]表示一共按了i次按钮到达了第j层,初始化f[0][s] = 1表示走0步就能到起点,最后答案在f[i][e]中(i是步数,枚举1 ~ n,从中找最小的来做i)表示走了i步到达了终点。状态转移方程是if(f[i - 1][j]) f[i][j + q[i]] = 1; f[i][j - q[i]] = 1;
- code :
1 #include <bits/stdc++.h> 2 #define INF 0x3f3f3f3f 3 using namespace std; 4 int n, q[1001], f[1001][1001], s, e; 5 signed main() 6 { 7 scanf("%d %d %d", &n, &s, &e); 8 for(register int i = 1; i <= n; ++i) 9 { 10 scanf("%d", &q[i]); 11 } 12 f[0][s] = 1; 13 for(register int i = 1; i <= n; ++i) 14 { 15 for(register int j = 1; j <= n; ++j) 16 { 17 if(f[i - 1][j]) 18 { 19 if(j + q[j] <= n)//记得判边界 20 { 21 f[i][j + q[j]] = 1; 22 } 23 if(j - q[j] >= 1) 24 { 25 f[i][j - q[j]] = 1; 26 } 27 } 28 } 29 } 30 for(register int i = 0; i <= n; ++i) 31 { 32 if(f[i][e]) 33 { 34 printf("%d", i); 35 return 0; 36 } 37 } 38 printf("-1"); 39 return 0; 40 }
二. 广搜 :
- 思路 :没啥特别的,直接从起点开始搜(向上搜,向下搜),f[i]表示从起点到i的最小步数
- code :
1 #include <bits/stdc++.h> 2 #define INF 0x3f3f3f3f 3 using namespace std; 4 int u[2] = {1, -1};//向上 + 向下 5 int n, s, e, q[100001], f[100001]; 6 struct node 7 { 8 int x, dis;//当前元素和从起点到x的距离 9 }; 10 inline void bfs()//开搜 11 { 12 memset(f, INF, sizeof(f)); 13 queue < node > pru; 14 pru.push(node{s, 0}); 15 f[s] = 0; 16 while(!pru.empty()) 17 { 18 node p = pru.front(); 19 pru.pop(); 20 for(register int i = 0; i < 2; ++i) 21 { 22 int nx = p.x + q[p.x] * u[i]; 23 if(nx >= 1 && nx <= n && f[nx] > p.dis + 1) 24 { 25 f[nx] = p.dis + 1; 26 pru.push(node{nx, f[nx]}); 27 } 28 } 29 } 30 return; 31 } 32 signed main() 33 { 34 scanf("%d %d %d", &n, &s, &e); 35 for(register int i = 1; i <= n; ++i) 36 { 37 scanf("%d", &q[i]); 38 } 39 bfs(); 40 if(f[e] == INF)//搜不到 41 { 42 printf("-1"); 43 } 44 else 45 { 46 printf("%d", f[e]); 47 } 48 return 0; 49 }