[UVA] Power Calculus

题目:https://vjudge.net/problem/UVA-1374

#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#pragma warning(disable:4996)
using namespace std;
const int maxn = 32;
int n;
int a[maxn];


bool dfs(int d, int maxd)
{
	if (a[d] == n) return true;
	if (d == maxd && a[d] != n) return false;

	int s = a[0];
	for (int i = 0; i <= d; i++)
	{
		s = max(s, a[i]);
	}

	if ((s << (maxd - d)) < n) return false;
	for (int i = d; i >= 0; i--)
	{
		a[d + 1] = s + a[i];
		if (dfs(d + 1, maxd)) return true;
		a[d + 1] = abs(s - a[i]);
		if (dfs(d + 1, maxd)) return true;

	}

	return false;
}

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

	return maxn;
}

int main()
{
	memset(a, 0, sizeof(a));
	a[0] = 1;
	while (cin >> n && n)
	{
		cout << solve() << endl;
	}
}

 

你可能感兴趣的:(C++)