2016ACM暑假集训 - Sticks

来源:互联网 发布:无人机传感器数据测试 编辑:程序博客网 时间:2024/05/21 15:01

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

95 2 1 5 2 1 5 2 141 2 3 40
 

Sample Output

65




解题思路:利用DFS,求出所有数的和,结果必定在最大值与和之间,然后再从最大的开始遍历即可。


代码:
#include <iostream>#include <algorithm>#include <cstdio>#include <cstring>using namespace std;int length[70];int use[70];int sum;int num;int n;int cmp(int a, int b){return a>b;}bool dfs(int len, int rlen, int number, int pos){if(num == number){return true;}if(len == sum){return true;}for(int i = pos; i < n; i++){if(!use[i]){if(length[i] + rlen == len){use[i] = true;if(dfs(len, 0, number+1, 0)){return true;}use[i] = false;}else if(length[i] + rlen < len){use[i] = true;if(dfs(len, length[i] + rlen, number, i+1)){return true;}use[i] = false;if(rlen == 0){return false;}while(length[i+1] == length[i]){i++;}}}}return false;}int main(){while(scanf("%d", &n) != EOF){if(n == 0){break;}memset(length, 0, sizeof(length));memset(use, 0, sizeof(use));sum = 0;for(int i = 0; i < n; i++){scanf("%d", &length[i]);use[i] = false;sum += length[i];}sort(length, length+n, cmp);if(length[0] > sum / 2){printf("%d\n", sum);continue;}for(int len = length[0]; len <= sum; len++){if(sum % len == 0){num = sum / len;if(dfs(len, 0, 0, 0)){printf("%d\n", len);break;}}}}return 0;}





0 0
原创粉丝点击