您的位置:首页 > 其它

UVA - 1374 Power Calculus 搜索(IDA*)枚举答案

2018-03-28 14:34 351 查看
开始以为对于每个n ,应该由跟他相邻的2的k次方的数得到,其实不然,
这里需要用到搜索的知识,因为解答树展开很大需要用到基于IDA*的剪枝;
知道题解以后假设最大深度为13,枚举答案maxd,当前深度达到maxd,或者当前集合中最大的数无法在maxd及之前达到目标值的话,返回;

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 10 + 3;
typedef long long ll;

int n;
int a[maxn + 1];

bool dfs(int maxd, int cnt) {

if(a[cnt] == n) return true;
if(cnt == maxd) return false;

int max_ = a[0];
for(int i = 1; i <= cnt; ++i) max_ = max(max_, a[i]);
if((max_<<(maxd-cnt)) < n) return false;

for(int i = cnt; i >= 0; --i) {
a[cnt+1] = a[cnt] + a[i];
if(dfs(maxd, cnt+1) ) return true;
a[cnt+1] = a[cnt] - a[i];
if(dfs(maxd, cnt+1) ) return true;
}
return false;
}

int solve(int n) {
if(n == 1) return 0;
a[0] = 1;
for(int i = 1; i < maxn; ++i) {
if(dfs(i, 0)) return i;
}
return maxn;
}

int main() {
while(scanf("%d", &n) == 1 && n) {
printf("%d\n", solve(n));
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: