UVA - 307 Sticks(dfs + 剪枝)

35 篇文章 0 订阅
11 篇文章 0 订阅

点击打开题目链接

George took sticks of the same length and cut them randomly until all parts became at most 50 units
long. Now he wants to return sticks to the original state, but he forgot how many sticks he had originally
and how long they were originally. Please help him and design a program which computes the smallest
possible original length of those sticks. All lengths expressed in units are integers greater than zero.

Input

The input file contains blocks of 2 lines. The first line contains the number of sticks parts after cutting.
The second line contains the lengths of those parts separated by the space. The last line of the file
contains ‘0’.

Output

The output file contains the smallest possible length of original sticks, one per line.

Sample Input

9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0

Sample Output

6
5

题目大意:乔治将很多相等长度的木棒砍成n个小木棒。希望你能拼成原来的样子,并使拼得的每个木棒长度最小。
思路:dfs+剪枝
①所有小木棒和一定能被原来木棒的根数整除并且原来木棒的长度一定≥现在每段小木棒的最大长度。
②木棒从长到短sort,提高dfs效率。
③如果当前木棒不能拼得,则下一个木棒如果与它长度相等,跳过。
④如果找不到某木棒之后得任意木棒可以与它拼得,直接返回false。因为这根木棒最后肯定孤立。

附上AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>

using namespace std;
const int maxn = 150;
int n;
int mind, sum;
int temp;
int a[maxn];
int vis[maxn];

int dfs(int cnt, int pos, int sum)
{
	if (cnt == n)
		return 1;
	for (int i = pos; i < n; i++)
	{
		if (vis[i])continue;
		if (sum + a[i] < temp)
		{
			vis[i] = 1;
			if (dfs(cnt + 1, i + 1, sum + a[i]))
				return 1;
			vis[i] = 0;
			while (a[i] == a[i + 1] && i + 1 < n)i++;//剪枝3:如果当前木棒拼不上并且下一个木棒长度和这个长度相等,则跳过
		}
		else if (sum + a[i] == temp)
		{
			vis[i] = 1;
			if (dfs(cnt + 1, 0, 0))
				return 1;
			vis[i] = 0;
			return 0;//剪枝2:如果当前木棒与后面所有木棒都拼不上;直接返回false;
		}
		if (sum == 0)
			return 0;
	}
	return 0;
}

int cmp(int a, int b)
{
	return a > b;
}

int main()
{
//	freopen("input","r",stdin);
//	freopen("output","w",stdout);
	ios::sync_with_stdio(false);
	while (cin >> n, n)
	{
		mind = 0;
		sum = 0;
		fill(a, a + maxn, 0);
		fill(vis, vis + maxn, 0);
		for (int i = 0; i < n; i++)
		{
			cin >> a[i];
			sum += a[i];
			mind = max(mind, a[i]);
		}
		sort(a , a + n , cmp);
		for (int i = n; i > 0; i--)
		{
			temp = sum/i;
			if (sum % i != 0 || temp < mind)continue;//剪枝1:不能被整除或者单个长度小于mind
			else
			{
				memset(vis, 0, sizeof(vis));
				if (dfs(0, 0, 0))
				{
					cout << temp << endl;
					break;
				}
			}
		}
		
	}
	return 0;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chook_lxk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值