poj1945 Power Hungry Cows BFS

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yalishiyanzhouyu888/article/details/52299122

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

题目大意
从数对(0, 1)开始,每次可以把两个数(可以取同一个数两次)相加或相减并替换原来的任意一个数,问得到给定的n的最少操作步数。

输入
一个整数n

输出
一个整数代表最少操作步数

这道题网上可以用A*启发式搜索做,但是我用的BFS。一开始犯了两个及其弱智的错误
1.pd函数未return
2.w=to.z忘记加1

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<string>
#include<vector>
#include<stack>
#include<set>
#include<queue>
using namespace std;
const int p1=20101,p2=97;
int n,m,ans;
struct node{
    int x,y,z;
};
queue <node> q;
bool hash[p1][p2];
node make(int x,int y,int z){
    node u;
    u.x=x;
    u.y=y;
    u.z=z;
    return u;
}
bool pd(int u,int v,int w){
    int i,j,k;
    if (u==n || v==n)
        return true;
    if (u<v) swap(u,v);
    if (u==v || u>=m || v>=p2)
        return false;
    if (!hash[u][v]){
        hash[u][v]=true;
        q.push(make(u,v,w));
    }
    return false;
}
int main(){
    scanf("%d",&n);
    m=n+p2;
    pd(1,0,0);
    while(!q.empty()){
        node to=q.front();
        q.pop();
        int u=to.x,v=to.y,w=to.z+1;
        if(pd(u+u,v,w) || pd(u+v,v,w) || pd(u+v,v,w) || pd(u,u+u,w) || pd(u,u+v,w) || pd(u,v+v,w) || pd(u,u-v,w) || pd(u-v,u,w)){
            ans=w;
            break;
        }
    }
    printf("%d\n",ans);
    return 0;
}
阅读更多

没有更多推荐了,返回首页