【例题 7-13 UVA-1374】Power Calculus

【链接】 我是链接,点我呀:)
【题意】

在这里输入题意

【题解】

结论:每次只用新生成的数字就好了。 然后就是IDA*了。 迭代深搜+剪枝。

【代码】

/*
  	1.Shoud it use long long ?
  	2.Have you ever test several sample(at least therr) yourself?
  	3.Can you promise that the solution is right? At least,the main ideal
  	4.use the puts("") or putchar() or printf and such things?
  	5.init the used array or any value?
  	6.use error MAX_VALUE?
  	7.use scanf instead of cin/cout?
  	8.whatch out the detail input require
*/
#include <bits/stdc++.h>
using namespace std;

int n,maxdep;

vector <int> v;
int pre[30];

bool dfs(int dep){
 	if (dep == maxdep){
		if (count(v.begin(),v.end(),n)) return true;
		return false;
 	}
 	int now = v.back();
 	int delta = maxdep - dep;
 	if (now*pre[delta]<n) return false;
	for (int i = (int) v.size()-1;i >= 0;i--){
		 	int temp = v[i] + now;
		 	if (count(v.begin(),v.end(),temp)==false){
		 	 	v.push_back(temp);
		 	 	if (dfs(dep+1)) return true;
		 	 	v.pop_back();
		 	}

		 	temp = now - v[i];
            if (count(v.begin(),v.end(),temp)==false){
		 	 	v.push_back(temp);
		 	 	if (dfs(dep+1)) return true;
		 	 	v.pop_back();
		 	}
 	}
 	return false;
}

int main(){
	#ifdef LOCAL_DEFINE
	    freopen("F:\c++source\rush_in.txt", "r", stdin);
	#endif
	pre[0] = 1;
	for (int i = 1;i < 30;i++) pre[i] = pre[i-1]*2;
	ios::sync_with_stdio(0),cin.tie(0);
	while (cin >>n && n){
		v.clear();
		v.push_back(1);
		for (maxdep = 0; ;maxdep++){
		 	if (dfs(0)){
		 		cout << maxdep << endl;
		 	 	break;
		 	}
		}
	}
	return 0;
}
原文地址:https://www.cnblogs.com/AWCXV/p/8039733.html