题意:给出x和正整数n,问最少需要几次乘除法可以得到x^n
思路:迭代搜索+减枝
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1010;
const int INF = 10000007;
int arr[MAXN],num;
int dfs(int n,int step){
if (num > step)
return 0;
if (arr[num] == n)
return 1;
if (arr[num] << (step-num) < n)
return false;
for (int i = 0; i <= num; i++){
num++;
arr[num] = arr[num-1] + arr[i];
if (arr[num] <= 10000 && dfs(n,step))
return true;
arr[num] = arr[num-1] - arr[i];
if (arr[num] > 0 && dfs(n,step))
return 1;
num--;
}
return 0;
}
int main(){
int n;
while (scanf("%d",&n) != EOF && n){
int i;
for (i = 0; ; i++){
arr[num = 0] = 1;
if (dfs(n,i))
break;
}
printf("%d\n",i);
}
return 0;
}