当前位置: 代码迷 >> 综合 >> HDU 1455 Sticks(dfs+强剪枝)
  详细解决方案

HDU 1455 Sticks(dfs+强剪枝)

热度:35   发布时间:2023-11-17 14:40:56.0

题目:

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<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<math.h>
#include<string>
#include<stdio.h>
#include<queue>
#include<stack>
using namespace std;
int n,tag,L;
int len[105];
int used[105];
bool cmp(int x,int y)
{return x>y;
}
bool dfs(int m,int left)
{if(m==0&&left==0)return true;if(left==0)left=L;int i,j;for(i=0;i<n;i++){if(!used[i]&&left>=len[i]){if(i>0){if(!used[i-1]&&len[i]==len[i-1])continue;}used[i]=1;if(dfs(m-1,left-len[i]))return true;else{used[i]=0;if(len[i]==left||left==L)return false;}}}return false;
}
int main()
{int i,j,sum;while(scanf("%d",&n)!=EOF&&n){tag=0;sum=0;for(i=0;i<n;i++){scanf("%d",&len[i]);used[i]=0;sum+=len[i];}sort(len,len+n,cmp);for(L=len[0];L<=sum/2;L++){if(sum%L)continue;if(dfs(n,L)){printf("%d\n",L);break;}}if(L>sum/2)printf("%d\n",sum);}return 0;
}