Square into Squares. Protect trees!

My little sister came back home from school with the following task:
given a squared sheet of paper she has to cut it in pieces which, when
assembled, give squares the sides of which form an increasing sequence
of numbers. At the beginning it was lot of fun but little by little we
were tired of seeing the pile of torn paper. So we decided to write a
program that could help us and protects trees.

Task Given a positive integral number n, return a strictly increasing
sequence (list/array/string depending on the language) of numbers, so
that the sum of the squares is equal to n².

If there are multiple solutions (and there will be), return as far as
possible the result with the largest possible values:

Examples decompose(11) must return [1,2,4,10]. Note that there are
actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1²

  • 2² + 4² + 10² but don’t return [2,6,9], since 9 is smaller than 10.

For decompose(50) don’t return [1, 1, 4, 9, 49] but [1, 3, 5, 8, 49]
since [1, 1, 4, 9, 49] doesn’t form a strictly increasing sequence.

Note Neither [n] nor [1,1,1,…,1] are valid solutions. If no valid
solution exists, return nil, null, Nothing, None (depending on the
language) or “[]” © ,{} (C++), [] (Swift, Go).

The function “decompose” will take a positive integer n and return the
decomposition of N = n² as:

[x1 … xk] or “x1 … xk” or Just [x1 … xk] or Some [x1 … xk] or
{x1 … xk} or “[x1,x2, … ,xk]” depending on the language (see
“Sample tests”)

Note for Bash decompose 50 returns “1,3,5,8,49” decompose 4 returns
“Nothing” Hint
翻译:
 给定一张边长为n的纸片,将其拆分不同边长的正方形,要求尽可能返回最大的边长,且不能为重复。

解法:
  这道题可以采用dfs,即深度搜索的解法,先从N-1开始搜索,将n2减去(n-1)2后的结果,继续向下寻找,将这些节点作为n-1的深度节点,如此,从最大值开始向下迭代,直到寻找到符合的结果。

  #include <vector>
#include <stack>
#include <algorithm>
class Decomp
{
public:
	static std::vector<long long> decompose(long long n)
	{
		std::stack<long long> resultstack;
		resultstack.push(n);
		long long Goal = 0;
		while (!resultstack.empty())
		{
			long long current = resultstack.top();
			resultstack.pop();
			Goal += current * current;
			for (long long i=current-1;i>0;i--)
			{
				long long iMul = i * i;
				if (Goal - iMul >=0)
				{
					resultstack.push(i);
					Goal -= iMul;
				}
				if (Goal ==0)
				{
					std::vector<long long> results;
					while (!resultstack.empty())
					{
						results.push_back(resultstack.top());
						resultstack.pop();
					}
					std::sort(results.begin(), results.end(), std::less<long long>());
					return results;
				}
			}
		}

		return std::vector<long long>();
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值