Sticks
时间限制:
3000 ms | 内存限制:
65535 KB
难度:
5
-
描述
-
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.
-
输入
- 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. 输出
- The output should contains the smallest possible length of original sticks, one per line. 样例输入
-
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
样例输出
-
6
5
-
思路:dfs+减枝
-
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int s[70]; bool vis[70]; int N; bool flag; int total;//原sticks个数 int cmp(int a,int b) { return a>b; } bool dfs(int cur,int curNum,int pos,int len) { if(curNum==total) return true; for(int i=pos;i<N;i++) { if(!vis[i]) { if(cur+s[i]==len)//匹配一组 { vis[i]=true; if(dfs(0,curNum+1,0,len))//匹配一组后,接着匹配下一组 return true; vis[i]=false; return false;//下一组匹配失败则说明,当前len值无法满足全部匹配条件,结束搜索 } if(cur+s[i]<len) { vis[i]=true; if(dfs(cur+s[i],curNum,i+1,len)) return true; vis[i]=false; if(cur==0) return false; // 说明找到了curNum<total个,剩下的无法匹配出len的长度 while(s[i]==s[i+1]) i++;//若s[i]不满足条件,则之后与s[i]相同长度的可忽略 } } } return false; } int main() { int max,sum; memset(s,0,sizeof(s)); while(scanf("%d",&N)&&N) { max=0; sum=0; for(int i=0;i<N;i++) { scanf("%d",&s[i]); vis[i]=false; if(s[i]>max) max=s[i]; sum+=s[i]; } sort(s,s+N,cmp);//优化 while(max<=sum) { total=sum/max; if(sum%max==0) { // printf("%d %d %d\n",max,sum,num); if(dfs(0,0,0,max)) { printf("%d\n",max); break; } } max++; } } return 0; }