hdu1445
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<bits/stdc++.h>
using namespace std;
int n, sum, genshu, len;//genshu表示木棍数,len表示需判断的木棍长度,sum为所有木棍总长度
int cd[100], vis[100];//vis数组标记 ,cd存储输入的木棍长度
bool cmp(int a, int b)
{
return a > b;
}
int dfs(int genshu2, int len2, int pos) {
if(genshu2 == genshu) return 1;//根数够了就退出dfs
if(len2 == len) return dfs(genshu2+1, 0, 0); //当拼完一根后,继续拼下一根
for(int i = pos; i < n; i++) {//按从大到小顺序搜索
if(vis[i]==0 && len2+cd[i] <= len)
{
vis[i] = 1;
if(dfs(genshu2, len2+cd[i], i+1)) return 1; //只有失败时会运行到下面
//下一个dfs中len2发生了改变
vis[i] = 0;
if(len2 == 0) return 0;
//巧妙,如果每次第一根拼接失败就退出 (这个剪枝一定有的,否则tle)!!!
}
}
return 0;
}
int main() {
while(cin>>n,n) {
sum = 0;
for(int i = 0; i < n; i++)
{
cin>>cd[i];
sum += cd[i];
}
sort(cd, cd+n, cmp);
for(int i = cd[0];; i++) //原木棍长度只会在cd[0]和总长度之间
{if(sum % i == 0)
{
memset(vis, 0, sizeof(vis));
len = i;
genshu = sum / len;
if(dfs(0, 0, 0)) break;
}
}
cout<<len<<endl;
}
return 0;
}