您的位置:首页 > 其它

POJ 1101 Sticks

2014-06-28 20:03 225 查看
F - Sticks
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%I64d
& %I64u
Submit Status

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 should 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


#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<string>
#include<map>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=105;
int done[MAXN];
int da[MAXN];
int n;
int sum,ssum,vecory,key;
int cmp(const void *a,const void *b){	return *(int *)a<*(int *)b?1:-1;}
bool dfs(int place,int ssum)
{ 
	if(place==n+1&&ssum==0)return 1;
    int i,j;
	if(ssum==0)ssum=key;
    for(i=1;i<=n;i++)
		if(!done[i]&&da[i]<=ssum)
		{
			if(!done[i-1]&&da[i]==da[i-1])continue;
			done[i]=1;
			if(dfs(place+1,ssum-da[i]))return 1;
			else
			{
				done[i]=0;
				if(ssum==key||ssum==da[i])return 0;
			}
		}
	return 0;
}
bool solve(int x)//测试x是否可行,为dfs初始化
{
	key=x;
	memset(done,0,sizeof(done));
	if(dfs(1,key))return 1;
	return 0;
}
int main()
{
	int m,i;
	freopen("123.txt","r",stdin);
	while(~scanf("%d",&n))
	{
		if(!n)break;
		int sum=0,max=0;
		for(i=1;i<=n;i++)//纪录最大值及总和
		{
			scanf("%d",&da[i]);
			if(da[i]>max)max=da[i];
			sum+=da[i];
		}
		if(n==1){printf("%d\n",max);continue;}
		qsort(da+1,n,sizeof(int),cmp);
		int num=sum/max;//num为最多可分根数,25/4,24/4都可以,不会漏解
		for(i=num;i>0;i--)
			if(sum%i==0&&solve(sum/i))break;//挨个测试,至少i为1时一定break;
		printf("%d\n",sum/i);
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: