• HDU 1548 A strange lift【BFS】


    题意:给出一个电梯,给出它的层数f,给出起点s,终点g,以及在每一层能够上或者下w[i]层,问至少需要按多少次按钮到达终点。

    和POJ catch that cow一样,直接用了那一题的代码,发现一直wa,

    后来才发现,POJ catch that cow是单组输入的,所以每次调用的时候不用清空队列,而这一题一次输入有多组数据---

    用这个清空队列

    while(!q.empty()) q.pop();

    #include<iostream>  
    #include<cstdio>  
    #include<cstring>  
    #include<algorithm>
    #include<queue>  
    #define maxn 100005
    using namespace std;
    queue<int> q;
    int visit[maxn],step[maxn],n,k,w[maxn],flag,t,sum;
    void bfs()
    {
        int head,next,i;
        while(!q.empty()) q.pop();   //注意调用前一定要清空 
        q.push(n);
        visit[n]=1;
        step[n]=0;
        while(!q.empty())
        {
            head=q.front(); q.pop();//取出 并弹出队首    
            for(i=1;i<=2;i++)
            {
                if(i==1) next=head-w[head];
                else  next=head+w[head];
                if(next>t||next<1) continue;//越界 
                          
    			if(!visit[next])//判重 
    			{
    				q.push(next);
                    visit[next]=1;
                    step[next]=step[head]+1;
    				  if(next==k) //找到终点 
                      {
                	   flag=1;
                	   sum=step[next];
    				   return;
                      }		
    			}                       
            }       
        }
        return;
    }
    int main()
    {
    	int i;
    	while(scanf("%d",&t)!=EOF&&t)
        {
        	memset(visit,0,sizeof(visit));
        //	memset(step,0,sizeof(step));//不用清空step数组 
        	
        	scanf("%d %d",&n,&k);
        	for(i=1;i<=t;i++) 
    		scanf("%d",&w[i]);
    		if(n==k) 
    		{
    			printf("0
    ");
    			continue;
    		}
    		flag=0;
    		bfs();
    		if(flag) printf("%d
    ",sum);
    		else printf("-1
    ");	
        }  
    }
    

      

  • 相关阅读:
    vue echarts 遇到的bug之一 无法渲染的问题
    前端SSR方案调研
    【读书笔记】数据结构与算法js描述-链表实现
    【转发】数组,字符串常用方法
    【转】README.md 语法汇总
    webpack 配置遇到的坑
    原生audio 实现音频播放器功能
    活动抽奖组件设计
    理解vue-loader
    kpi sql 积累
  • 原文地址:https://www.cnblogs.com/wuyuewoniu/p/4287443.html
Copyright © 2020-2023  润新知