hdu-1548 A strange lift --- BFS

Topic link:

http://acm.hdu.edu.cn/showproblem.php?pid=1548

Topic meaning:

One day Tongtong had a dream about a very strange elevator. Each floor of the building can stop the elevator, and there is a number K on the i-th floor (1≤i≤N); (0≤Ki≤N). The elevator has only four buttons: on, off, up, down. The number of floors above and below is equal to the number on the current floor. Of course, if the requirements are not met, the corresponding button will fail. For example: 3 3 1 2 5 represents Ki (K1=3, K2=3,…), starting from the first floor. On the first floor, pressing "Up," can go to the 4th floor, but pressing "Down" does not work, because there is no -2 floor. So, what is the minimum number of button presses required to get from building A to building B?

Problem solving ideas:

Direct BFS

Here dijkstra also works

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int maxn = 1000 + 10;
 4 const int INF = 0x3f3f3f3f;
 5 int c[maxn];
 6 bool vis[maxn];
 7 struct node
 8 {
 9     int x, step;
10     node(int x, int step):x(x), step(step){}
11 };
12 int n;
13 void BFS(int s, int t)
14 {
15     memset(vis, 0, sizeof(vis));
16     vis[s] = 1;
17     queue<node>q;
18     q.push(node(s, 0));
19     while(!q.empty())
20     {
21         node now = q.front();
22         //cout<<now.x<<" "<< now.step<<endl;
23         q.pop();
24         if(now.x == t)
25         {
26             cout<<now.step<<endl;
27             return;
28         }
29         int x = now.x + c[now.x];
30         if(x <= n && !vis[x])q.push(node(x, now.step + 1)), vis[x] = 1;
31         x = now.x - c[now.x];
32         if(x > 0 && !vis[x])q.push(node(x, now.step + 1)), vis[x]  =1;
33     }
34     cout<<"-1"<<endl;
35 }
36 int main()
37 {
38     while(cin >> n && n)
39     {
40         int a, b;
41         cin >> a >> b;
42         for(int i = 1; i <= n; i++)cin >> c[i];
43         BFS(a, b);
44     }
45     return 0;
46 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324609191&siteId=291194637