sticks

来源:互联网 发布:五笔输入法下载mac版 编辑:程序博客网 时间:2024/05/16 08:58
Sticks
Time Limit: 1000MS Memory Limit: 10000KTotal Submissions: 113467 Accepted: 26051

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

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

Sample Output

65

思路:深搜, 加好多剪枝。

#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>using namespace std;#define MAX 70int temp[MAX], n, mark[MAX];bool cmp(int a, int b){return a > b;}int dfs(int len, int lenleft, int num)       //深搜求解(len,每段长度, lenleft, 剩余长度, num, 剩余木棍数){if(lenleft == 0 && num == 0)             //剩余量为0,说明已找到{return 1;}if(lenleft == 0)                          //num不为0,未拼完, 初始化lenleft, 继续拼下一根{lenleft = len;}for(int i = 0; i < n; i++){if(mark[i])                           //已经用过,跳过{continue;}if(temp[i] <= lenleft)                 //比lenleft段才能拼进去{mark[i] = 1;if(dfs(len, lenleft-temp[i], num-1)) //能拼完?,返回成功 {return 1;}mark[i] = 0;                          //标记回来if(temp[i] == lenleft || lenleft == len)  //若正好可以拼完一根,最后都失败了, 那后面就不用搜了, 注定失败{break;}while(temp[i] == temp[i+1]){i++;                                //跳过同等长度(已经失败, 再搜就是浪费时间)}}}return 0;}int main(){int len, i;while(scanf("%d", &n) && n != 0){len = 0;for(i = 0; i < n; i++){scanf("%d", &temp[i]);len += temp[i];}sort(temp, temp+n, cmp);                    //从小到大排个序for(i = temp[0]; i <= len; i++)              //从最长的开始{memset(mark, 0, sizeof(mark));if(len % i != 0)                         //不整除的话,没法拼{continue;}else{if(dfs(i, i, n))                      //找到的第一个就是最小结果{printf("%d\n", i);break;}}}}return 0;}


原创粉丝点击