【HDU2717】-Catch that cow

题目地址:

http://acm.hdu.edu.cn/showproblem.php?pid=2717


这点需要特别注意的是HDU特别坑爹,POJ上是单组数据,多点测试,HDU是一点测试,多组数据!所以在POJ上把while(cin >> N >> K)去掉也是AC的,简单的BFS

#include <iostream>
#include <stdio.h>
#include <queue>
#include <stdlib.h>
#include <memory.h>
//#define DBG
using namespace std;
const long MAXSIZE = 110000;
struct node
{
    long depth;
    long value;
};
long N,K;
int Visited[MAXSIZE];
void BFS()
{
    node tmp;
    node val;
    queue<node> q;
    memset(Visited,0,sizeof(int)*MAXSIZE);
    tmp.value = N;
    tmp.depth = 0;
    q.push(tmp);
    while(!q.empty())
    {
        tmp = q.front();
        q.pop();
        if(tmp.value == K) break;
        else
        {
          if(Visited[tmp.value])
          {
             continue;
          }
          else
          {
            Visited[tmp.value] = 1;
            val.depth = tmp.depth + 1;
            if(tmp.value + 1 < MAXSIZE)
            {
                val.value = tmp.value + 1;
                q.push(val);
            }
            if(tmp.value - 1 >= 0)
            {
                val.value = tmp.value -1;
                q.push(val);
            }
            if(tmp.value * 2 < MAXSIZE)
            {
                val.value = tmp.value * 2;
                q.push(val);
            }
          }
        }
//BFS NOW
    }
    cout << tmp.depth << endl;
}
int main(int argc,char* argv[])
{
    while(cin >> N >> K)
    {
        if(N > K)
            cout << N - K << endl;
        else if (N == K)
                cout << "0" << endl;
        else // N < K
        {
            BFS();
        }
    }
    return 0;
}


你可能感兴趣的:(【HDU2717】-Catch that cow)