您的位置:首页 > 其它

poj3134迭代加深搜索

2016-05-05 14:31 176 查看
题目大意:给你一个n,让你从x出发只用乘除法,求最小的次数算出x^n,所有的使用乘方必须已知即曾经计算出来。

思路:迭代加深搜索。n不超过1000,所以最深出现答案的层数不会太深,可以试用跌代加深搜索。即每次设定搜索层数,判断该层是否有解。若有解输出改成即可。需要剪枝操作。

#include <algorithm>
#include <set>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <iostream>

using namespace std;

#define maxn 1000010
#define mem(a , b)  memset(a , b , sizeof(a))
#define LL long long

int val[maxn];
int pos , n;

bool dfs(int num , int depth)
{
if(num > depth) return false;
if(val[pos] == n)  return true;
if(val[pos] << (depth - num) < n) return false;
pos ++ ;
for(int i = 0 ; i < pos ; i ++)
{
val[pos] = val[pos-1] + val[i];
if(dfs(num + 1, depth)) return true;
val[pos] = abs(val[pos-1] - val[i]);
if(dfs(num + 1, depth)) return true;
}
pos -- ;
return false;
}

int main()
{
int t;
while(scanf("%d" , &n) != EOF && n)
{
int i;
for(i = 0 ; ; i ++)
{
val[pos = 0] = 1;
if(dfs(0 , i)) break;
}
cout << i << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: