
本文共 2058 字,大约阅读时间需要 6 分钟。
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 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’.
Output
The output file 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
题意
乔治拿起同样长度的棍子,随意剪,直到所有部分都变成最多50个单位
长的。现在他想把棍子恢复到原来的状态,但他忘了原来有多少根棍子了
以及它们最初有多长。请帮他设计一个计算最小值的程序
可能的原始长度。所有以单位表示的长度都是大于零的整数。
输入
输入文件包含2行的块。第一行包含切割后的木棒零件数。
第二行包含由空格分隔的部分的长度。文件的最后一行
包含“0”。
输出
输出文件包含最小长度的原始棒,每行一个。
代码
#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int a[100234],book[100234];int len,n,cnt;int bi(int x,int y){ return x>y;}int dfs(int sum,int nowl,int wei){ int i; if(sum==cnt)//段数已经够 return 1; if(nowl==len)//凑成一个len,sum+1,继续找 return dfs(sum+1,0,1); int chong=0; for(i=wei;i<=n;i++) { if(book[i]==0&&nowl+a[i]<=len&&chong!=a[i]) { book[i]=1; chong=a[i]; if(dfs(sum,nowl+a[i],i)) return 1; book[i]=0;//记得清理标记 if(nowl==0)//剪枝,否则time limit //nowl==0,说明当前的nowl不能组成len,(遍历了一遍边都不行,说明它不可用) //可以不写a[i]+nowl==len这个剪枝, 因为if(dfs(sum,nowl+a[i],i))调用已经处理过了如果成立的话就return 1了不会到后面 return 0; } } return 0;}int main(){ int i,j; while(~scanf("%d",&n)) { if(n==0) break; int sum=0; for(i=1;i<=n;i++) { scanf("%d",&a[i]); sum+=a[i]; } sort(a+1,a+1+n,bi); for(len=a[1];len<=sum;len++)//从最长的a[1]开始 { if(sum%len==0) { memset(book,0,sizeof(book)); cnt=sum/len; if(dfs(1,0,1)) break; } } printf("%d\n",len); } return 0; }
发表评论
最新留言
关于作者
