【BFS搜索】poj1945 Power Hungry Cows

来源:互联网 发布:2013网络购物交易额 编辑:程序博客网 时间:2024/06/19 04:08

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 101using 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 0
原创粉丝点击