zoukankan      html  css  js  c++  java
  • poj3278 Catch That Cow

    题意:

    在同一数轴上,有一头奶牛坐标为k,农夫的坐标为n,要从n运动到k。
    有三种方法:
    1. 从当前位置x运动到x+1
    2. 从当前位置x运动到x-1
    3. 当前位置x运动到2*x

    思路:

    裸裸的BFS不想多解释

    直接上代码

    #include <iostream>
    #include <cstdio>
    #include <cstdlib>
    #include <cstring>
    #include <algorithm>
    #include <algorithm>
    #include <queue>
    using namespace std;
    const int N=100000;
    int n,k,ans[N+5];
    bool flag[N+5];
    queue<int>f;
    
     int bfs(int n,int k)
    {
    	f.push(n);  ans[n]=0; flag[n]=1;
    	int res,tmp;
    	while (!f.empty())
    	{
    		res=f.front(); f.pop();
    		if (res==k) return ans[res];
    		for (int i=0; i<=2; i++)
    		{
    			if (i==0) tmp=res+1;
    			else if (i==1) tmp=res-1;
    			else tmp=res*2;
    			if (tmp<0||tmp>N) continue;
    			if (!flag[tmp])
    			{
    				f.push(tmp);
    				flag[tmp]=1; ans[tmp]=ans[res]+1;  
    			}
    		}
    	}
    }
    
     int main()
    {
    	scanf("%d%d",&n,&k);
    	if (n>=k) printf("%d\n",n-k);
    	else printf("%d\n",bfs(n,k));
    	return 0;
    }
    
  • 相关阅读:
    层叠
    属性值的计算过程
    HTML+CSS笔记1-杂
    C语言—栈
    C语言零碎知识点
    线性表,顺序表,链表,数组的区别与联系
    C语言—单链表
    转载——从机器学习谈起
    readonly和const关键字
    C#中的扩展方法
  • 原文地址:https://www.cnblogs.com/lyxzhz/p/11405248.html
Copyright © 2011-2022 走看看