hdu1455 Sticks ----DFS

原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1455


一:原题内容

Problem Description
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 contains blocks of 2 lines. The first line contains the number of sticks parts after cutting, there are at most 64 sticks. The second line contains the lengths of those parts separated by the space. The last line of the file contains zero.

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

二:分析理解

原先有若干 等长 的棍,被人折断了,现在要你还原成这些等长的棍,当然不一定能还原成起初的长度,所以求出可以还原的等长的最小长度。


三:AC代码

#include<iostream>
#include<algorithm>

using namespace std;

struct Stick
{
	int m_length;//木棒的长度
	bool m_used;//木棒是否被使用过
};

Stick g_stick[70];
int g_total, g_length;//能组成的木棒的组数;组成的木棒的长度
int n, g_sum;//输入的木棍个数;木棍总长度

bool cmp(Stick s1, Stick s2)
{
	return s1.m_length > s2.m_length;
}

/* 已组成的木棒数目;已经组成的长度;搜索的木棒的下标的位置 */
bool Dfs(int c, int len, int pos)
{
	if (c == g_total) return true;
	for (int i = pos + 1; i < n; i++)
	{
		if (g_stick[i].m_used) continue;
		if (len + g_stick[i].m_length == g_length)
		{
			g_stick[i].m_used = true;
			if (Dfs(c + 1, 0, -1))
				return true;
			g_stick[i].m_used = false;
			return false;
		}
		else if (g_stick[i].m_length + len < g_length)
		{
			g_stick[i].m_used = true;
			if (Dfs(c, len + g_stick[i].m_length, i))
				return true;
			g_stick[i].m_used = false;
			if (len == 0)
				return false;
			while (g_stick[i].m_length == g_stick[i + 1].m_length)
				i++;
		}
	}
	return false;
}
int main()
{
	while (~scanf("%d", &n) && n)
	{
		g_sum = 0;
		for (int i = 0; i < n; i++)
		{
			scanf("%d", &g_stick[i].m_length);
			g_sum += g_stick[i].m_length;
			g_stick[i].m_used = false;
		}

		sort(g_stick, g_stick + n, cmp);

		//从木棒的最长的那根开始搜索,因为最小的组合也会大于等于最长的那根
		for (g_length = g_stick[0].m_length; g_length <= g_sum; g_length++)
		{
			if (g_sum%g_length) continue;
			g_total = g_sum / g_length;//得到木棒总数目
			if (Dfs(0, 0, -1))
			{
				printf("%d\n", g_length);
				break;
			}
		}
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值