【题目描述】
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.
乔治拿出同样长的棍子,随意地剪,直到所有的部分都长到最多50个单位。现在他想把棍子还给原来的状态,却忘了原来有多少根棍子,也忘了原来有多少根棍子。请帮助他,并设计一个程序,计算尽可能最小的原始长度的这些棍子。以单位表示的所有长度都是大于零的整数。
【输入】
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’.
输入的每块包括两行,第一行是在剪完后的棍子数量,第二行是每段棍子的长度用空格隔开,最后一行以0结束
【输出】
The output file contains the smallest possible length of original sticks, one per line.
输出文件包含最小的原始棒长度,每行一个。
【样例输入】
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
【样例输出】
6
5
题目链接:https://cn.vjudge.net/problem/UVA-307
DFS+剪枝,不剪枝会T
代码如下:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
static const int MAXN=100;
bool vis[MAXN+10];
int n,a[MAXN+10],sum,num;
bool dfs(int s,int x,int cnt)
{
if(cnt==n)
return 1;
for(int i=x;i<n;i++)
{
if(vis[i])
continue;
if(s+a[i]<num)
{
vis[i]=1;
if(dfs(s+a[i],i+1,cnt+1))
return 1;
vis[i]=0;
while(i+1<n && a[i]==a[i+1]) i++;
}
else if(s+a[i]==num)
{
vis[i]=1;
if(dfs(0,0,cnt+1))
return 1;
vis[i]=0;
return 0;
}
if(s==0)
return 0;
}
return 0;
}
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0),cout.tie(0);
while(cin>>n && n)
{
sum=0;
memset(a,0,sizeof(a));
for(int i=0;i<n;i++)
{
cin>>a[i];
sum+=a[i];
}
sort(a,a+n,cmp);
for(int i=n;i>=1;i--)
{
num=sum/i;
if(sum%i || a[0]>num)
continue;
memset(vis,false,sizeof(vis));
if(dfs(0,0,0))
{
cout<<num<<endl;
break;
}
}
}
return 0;
}