• 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
  • 相关阅读:
    nginx 配置https 负载均衡
    MyCAT+MySQL搭建高可用企业级数据库集群视频课程
    Java数字签名算法--RSA
    bootstrap在iframe框架中实现由子页面在顶级页面打开模态框(modal)
    bootstrap-treeview 自定义实现双击事件
    Java多线程之内存可见性
    Java实现责任链模式
    JVM(HotSpot) 7种垃圾收集器的特点及使用场景
    jQuery的noConflict以及插件扩展
    JavaScript事件漫谈
  • 原文地址:https://www.cnblogs.com/wikioibai/p/4392648.html
Copyright © 2020-2023  润新知