首页 > 代码库 > TYVJ P3522 &&洛谷 P1135 奇怪的电梯 Label:bfs
TYVJ P3522 &&洛谷 P1135 奇怪的电梯 Label:bfs
题目描述
呵呵,有一天我做了一个梦,梦见了一种很奇怪的电梯。大楼的每一层楼都可以停电梯,而且第i层楼(1<=i<=N)上有一个数字Ki(0<=Ki<=N)。电梯只有四个按钮:开,关,上,下。上下的层数等于当前楼层上的那个数字。当然,如果不能满足要求,相应的按钮就会失灵。例如:3 3 1 2 5代表了Ki(K1=3,K2=3,……),从一楼开始。在一楼,按“上”可以到4楼,按“下”是不起作用的,因为没有-2楼。那么,从A楼到B楼至少要按几次按钮呢?
输入输出格式
输入格式:
输入文件共有二行,第一行为三个用空格隔开的正整数,表示N,A,B(1≤N≤200, 1≤A,B≤N),第二行为N个用空格隔开的正整数,表示Ki。
输出格式:
输出文件仅一行,即最少按键次数,若无法到达,则输出-1。
输入输出样例
输入样例#1:
LIFT.IN5 1 53 3 1 2 5
输出样例#1:
LIFT.OUT3
代码
正解1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<queue> 6 #include<vector> 7 using namespace std; 8 struct cc{ 9 int num,step;10 };11 12 cc make_cc(int num,int step){13 cc a;14 a.num=num;a.step=step;15 return a;16 }17 18 int a[100005],vis[100005],N,A,B,cnt;19 queue<cc> que;20 int main(){21 // freopen("01.in","r",stdin);22 // freopen("01.out","w",stdout);23 24 scanf("%d%d%d",&N,&A,&B);25 for(int i=1;i<=N;i++){26 scanf("%d",&a[i]);27 }28 29 que.push(make_cc(A,0));30 vis[A]=1;31 while(!que.empty()){32 cc tmp=que.front();que.pop();33 34 if(tmp.num==B){35 printf("%d\n",tmp.step);36 return 0;37 }38 39 int low=tmp.num-a[tmp.num],high=tmp.num+a[tmp.num];40 41 if(low>=1 && !vis[low]){42 que.push(make_cc(low,tmp.step+1));vis[low]=1;43 }44 if(high<=N && !vis[high]){45 que.push(make_cc(high,tmp.step+1));vis[high]=1;46 }47 }48 49 puts("-1");50 51 // fclose(stdin);52 // fclose(stdout);53 return 0;54 }
错误代码1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<queue> 6 #include<vector> 7 using namespace std; 8 int a[100005],vis[100005],N,A,B,cnt; 9 queue<int> que;10 int main(){11 // freopen("01.in","r",stdin);12 // freopen("01.out","w",stdout);13 14 scanf("%d%d%d",&N,&A,&B);15 for(int i=1;i<=N;i++){16 scanf("%d",&a[i]);17 }18 19 que.push(A);20 vis[A]=1;21 while(!que.empty()){22 int tmp=que.front();que.pop();23 int low=tmp-a[tmp],high=tmp+a[tmp];24 25 if(tmp==B){26 printf("%d\n",cnt);27 return 0;28 }29 30 if(low>0&&!vis[low]){31 que.push(low);vis[low]=1;32 }33 if(high<=N&&!vis[high]){34 que.push(high);vis[high]=1;35 }36 cnt++;37 }38 39 puts("-1");40 41 // fclose(stdin);42 // fclose(stdout);43 return 0;44 }错误代码是没有考虑到cnt可能不符合当前的步数
因为没理解好bfs导致错误,cnt一直增加,而步数是随bfs深度增加的
TYVJ P3522 &&洛谷 P1135 奇怪的电梯 Label:bfs
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。