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;
}
这里需要用到搜索的知识,因为解答树展开很大需要用到基于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;
}
相关文章推荐
- UVA - 1374 Power Calculus :IDA* 各种优化
- UVa 1374 - Power Calculus(IDA*)
- UVa 1374:Power Calculus(IDA*)
- Power Calculus UVA - 1374(IDA* 状态空间搜索)
- UVA 1374 ——Power Calculus(IDA*搜索)
- UVa 1374 Power Calculus (IDA*或都打表)
- UVA - 1374 Power Calculus【IDA*】
- UVA 1374 Power Calculus(IDA*)
- UVa 1374 - Power Calculus ( IDA* - 迭代加深搜索 )
- [IDA*] UVa1374 Power Calculus 快速幂计算
- UVA 1374 Power Calculus
- Power Calculus UVA - 1374
- UVA 1374(p211)----Power Calculus
- UVA 1374 Power Calculus——暴力打表
- UVA1374PowerCalculus
- UVa 1374 Power Calculus (快速幂计算)
- Power Calculus UVA - 1374 迭代加深搜索
- UVA - 1374 - Power Calculus(迭代加深)
- UVA - 1374 Power Calculus
- UVa 1374 - Power Calculus <IDA*算法>