hdu 1548 A strange lift (bfs)

题目链接:http://icpc.njust.edu.cn/Problem/Hdu/1548/

题目大意:给定一个楼层、起始点和终点,每个楼可上可下一个长度,求重起始点到终点的最少上下次数。

代码如下:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 typedef unsigned int ui;
 4 typedef long long ll;
 5 typedef unsigned long long ull;
 6 #define pf printf
 7 #define mem(a,b) memset(a,b,sizeof(a))
 8 #define prime1 1e9+7
 9 #define prime2 1e9+9
10 #define pi 3.14159265
11 #define lson l,mid,rt<<1
12 #define rson mid+1,r,rt<<1|1
13 #define scand(x) scanf("%llf",&x) 
14 #define f(i,a,b) for(int i=a;i<=b;i++)
15 #define scan(a) scanf("%d",&a)
16 #define dbg(args) cout<<#args<<":"<<args<<endl;
17 #define inf 0x3f3f3f3f
18 #define maxn 1005
19 #define maxm 2000010
20 int n,m,t,a,b;
21 int st,ed;
22 int k[maxn];
23 bool vis[maxn];
24 struct node{
25     int x,step;
26     node(int x,int step):x(x),step(step){};
27     node(){};
28 };
29 node cur,nxt;
30 int bfs()
31 {
32     queue<node>q;
33     node st(a,0);
34     vis[a]=true;//一旦到达该楼层 
35     q.push(st);
36     while(!q.empty())
37     {
38         cur=q.front();
39         q.pop();
40         if(cur.x==b)
41         {
42             return cur.step;
43             //由于队列前面的状态结点的step值一定大于等于后面结点的step值,所以第一次达到目标状态的step一定是最优值 
44         }
45         if(cur.x+k[cur.x]<=n&&cur.x+k[cur.x]>0&&!vis[cur.x+k[cur.x]])
46         {
47             vis[cur.x+k[cur.x]]=true;
48             nxt.x=cur.x+k[cur.x];
49             nxt.step=cur.step+1;
50             q.push(nxt);
51         }
52         if(cur.x-k[cur.x]<=n&&cur.x-k[cur.x]>0&&!vis[cur.x-k[cur.x]])
53         {
54             vis[cur.x-k[cur.x]]=true;
55             nxt.x=cur.x-k[cur.x];
56             nxt.step=cur.step+1;
57             q.push(nxt);
58         }
59     }
60     return -1;
61 }
62 int main()
63 {
64     //freopen("input.txt","r",stdin);
65     //freopen("output.txt","w",stdout);
66     std::ios::sync_with_stdio(false);
67     while(scan(n)&&n)
68     {
69         scan(a);
70         scan(b);
71         mem(vis,false);
72         f(i,1,n)scan(k[i]);
73         pf("%d\n",bfs());
74     }
75  } 

猜你喜欢

转载自www.cnblogs.com/randy-lo/p/12507196.html