题目大意:给出 n,问说至少计算几步得到 x^n。
解题思路:迭代深搜,枚举步数,然后深搜判断是否可行。需要优化,当当前数 now 按照最大方案执行后仍然小于 n,则说明不可行。
#include <cstdio>
int n, MAX, A[35];
bool DFS(int cur, int now){
if (cur > MAX || now <= 0 || now << (MAX - cur) < n)
return false;
if (now == n || now << (MAX - cur) == n)
return true;
A[cur] = now;
for (int i = 0; i <= cur; ++i) {
if (DFS(cur + 1, now + A[i]))
return true;
if (DFS(cur + 1, now - A[i]))
return true;
}
return false;
}
int main() {
while (scanf("%d", &n), n) {
for (MAX = 0; !DFS(0, 1); ++MAX);
printf("%d\n", MAX);
}
return 0;
}
时间: 2024-12-14 10:43:46