E - Sticks
Crawling in process...
Crawling failed
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
Description
Input
Output
Sample Input
Sample Output
Hint
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
9
5 2 1 5 2 1 5 2 1
4
1 2 3 4
0
Sample Output
6
5
n根长度不等的小棍,接成一些等长的长棍,求最小长度是多少?
使用贪心+dfs,从最长的小棍开始搜索
注意dfs中的逻辑
#include<cstdio> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> using namespace std; const int maxn=70; int n,sum,aim,num,a[maxn]; bool used[maxn]; int cmp(int x,int y) { if(x>y) return 1; else return 0; } bool dfs(int stick,int len,int pos) { int i; bool sign=(len==0?true:false); if(stick==num) return true; for(i=pos+1;i<n;i++) { if(used[i]) continue; if(len+a[i]==aim) { used[i]=true; if(dfs(stick+1,0,-1)) return true; used[i]=false; return false; } else if(len+a[i]<aim) { used[i]=true; if(dfs(stick,len+a[i],i)) return true; used[i]=false; if(sign) return false; while(a[i]==a[i+1]) i++; } } return false; } int main() { while(scanf("%d",&n)==1) { if(n==0) break; sum=0; for(int i=0;i<n;i++) { scanf("%d",&a[i]); sum+=a[i]; } sort(a,a+n,cmp); for(aim=a[0];aim<=sum;aim++) if(sum%aim==0) { num=sum/aim; memset(used,false,sizeof(used)); if(dfs(1,0,-1)) { printf("%d\n",aim); break; } } } return 0; }