【BFS搜索】poj1945 Power Hungry Cows

Description

FJ’s cows would like to be able to compute integer powers P (1 <= P <= 20,000) of numbers very quickly, but need your help. Because they’re going to be computing powers of very large numbers, they can only keep around two work variables for intermediate results.

The first of those work variables is initialized to the number (denoted x) for which they are calculating the power; the other is initialized to 1. The cows can both multiply and divide any pair of the work variables and store the result in any work variable, but all results are stored as integers.

For example, if they want to compute x^31, one way to perform the calculation is:
WV1 WV2

                                  Start:   x    1

Multiply first by first, store in second: x x^2

              Multiply second by second:   x   x^4

              Multiply second by second:   x   x^8

              Multiply second by second:   x   x^16

              Multiply second by second:   x   x^32

                 Divide second by first:   x   x^31

Thus, x^31 can computed in six operations. Given the power to be computed and the the number of work variables, find the minimum number of operations to calculate the power.

Input

A single line with one integer: P.
Output

A single line with a single integer that is the minimum number of operations it requires to compute the power.
Sample Input

31
Sample Output

6

题目大意:对(1,0)进行操作得到n,求最少操作次数。

第一反应是BFS搜索。当然也可以用A*算法
在实现过程中注意搜索顺序,否则就会RE,TLE。= =
因为担心用STL会超时就手写的队列,至于数组的大小嘛,经多次实验得到的……
具体操作见代码。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#define MAXN 20110
#define MAXM 101
using namespace std;

int n ,head ,last ,q[700003][3] ,n2 ;
bool visit[MAXN][MAXM] ;

bool add(int wv1,int wv2,int step)
{
    if(wv1==n||wv2==n)
        return true;
    if(wv1<wv2)//将大的放在前面
    {
        int temp=wv2;
        wv2=wv1 ,wv1=temp ;
    }
    if(wv1==wv2||wv1>=n2||wv2>=MAXM)
        return false;
    if(!visit[wv1][wv2])
    {
        visit[wv1][wv2]=1;
        ++last;
        q[last][0]=wv1 ,q[last][1]=wv2 ,q[last][2]=step;
    }
    return false;
}

void bfs()
{
    add(1,0,0);
    int wv1 ,wv2 ,step ;
    while(head<last)
    {
        ++head;
        wv1=q[head][0] ,wv2=q[head][1] ,step=q[head][2]+1 ;
        if(add(wv1+wv1,wv2,step)||add(wv1+wv2,wv2,step)||add(wv2+wv2,wv2,step)||add(wv1,wv1+wv1,step)||add(wv1,wv1+wv2,step)||add(wv1,wv2+wv2,step)||add(wv1,wv1+wv2,step)||add(wv1,wv1-wv2,step)||add(wv1-wv2,wv1,step))
        {
            //这里有贪心的方法:将大的先入队
            printf("%d\n",step);
            return;
        }
    }
    return;
}

int main()
{
    scanf("%d",&n);
    n2=n+MAXM;
    bfs();
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值