• POJ 3278 Catch That Cow(BFS基础)


    题目大意:

      给你两个数字,n和k,对于n有三种变化规则。

      1.n->n-1;

      2.n->n+1;

      3.n->2*n;

      使得n==k,问如何需要最少的操作次数。

    解题思路:

      凡是有关最少操作次数的问题,就归结为bfs来求解,这道题是一个三入口式的bfs。。。

    在搜索的过程中,一定要注意是否有需要剪纸的必要,不然蛮力上的话,必然会导致RE。

    代码:

    # include<cstdio>
    # include<iostream>
    # include<algorithm>
    # include<functional>
    # include<cstring>
    # include<string>
    # include<cstdlib>
    # include<iomanip>
    # include<numeric>
    # include<cctype>
    # include<cmath>
    # include<ctime>
    # include<queue>
    # include<stack>
    # include<list>
    # include<set>
    # include<map>
    
    using namespace std;
    
    const double PI=4.0*atan(1.0);
    
    typedef long long LL;
    typedef unsigned long long ULL;
    
    # define inf 999999999
    # define MAX 100000+4
    
    int step[MAX];
    int book[MAX];
    int n,k;
    int ans;
    queue<int>Q;
    
    int bfs( int n,int k )
    {
        int next,head;
        step[n] = 0;
        book[n] = 1;
        Q.push(n);
        while ( !Q.empty() )
        {
            head = Q.front();
            Q.pop();
            for ( int i = 0;i < 3;i++ )
            {
                if ( i==0 )
                    next = head-1;
                else if ( i==1 )
                    next = head+1;
                else
                    next = 2*head;
                if ( next>MAX||next<0 )
                    continue;
    
                if ( book[next]==0 )
                {
                    book[next] = 1;
                    Q.push(next);
                    step[next] = step[head]+1;
                }
                if ( next==k )
                    return step[next];
            }
    
        }
    }
    
    int main(void)
    {
        while ( cin>>n>>k )
        {
            while ( !Q.empty() )
            Q.pop();
            ans = 0;
            memset(step,0,sizeof(step));
            memset(book,0,sizeof(book));
            if ( n>=k )
                ans = n-k;
            else
                ans = bfs(n,k);
            cout<<ans<<endl;
        }
    
    
        return 0;
    }
    View Code
  • 相关阅读:
    php 基础------数组过滤
    js或者jq 使用cookie 时在谷歌浏览器不好使
    css3 -阻止元素成为鼠标事件目标 pointer-events
    CSS3-----transform 转换
    css3---过渡
    css3动画----animation
    移动端尺寸适配--媒体查询
    工作一年总结
    关于Jquery.Data()和HTML标签的data-*属性
    android shape
  • 原文地址:https://www.cnblogs.com/wikioibai/p/4392648.html
Copyright © 2020-2023  润新知