您的位置:首页 > 其它

hdu1455 Sticks ----DFS

2016-05-17 17:25 337 查看
原题链接: http://acm.hdu.edu.cn/showproblem.php?pid=1455
一:原题内容

[align=left]Problem Description[/align]
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.

 
[align=left]Input[/align]
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.

[align=left]Output[/align]
The output file contains the smallest possible length of original sticks, one per line.

 
[align=left]Sample Input[/align]

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

 
[align=left]Sample Output[/align]

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: