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.
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
6 5
解题思路:
这其实就是dfs,但是直接dfs就会超时,要去剪枝,将所有的树枝排序,如果第一个是不符合的,比如说需要达到的长度是10,当前的长度是8,但是后面序列里,并没有长度为2的,那么8后面的情况都不需要考虑了,然后还有一些基础的剪枝
代码:
#include<iostream> #include<cmath> #include<cstring> #include<algorithm> using namespace std; int a[100]; int sum,maxx; int t; bool flag; int vis[100]; bool cmp(int a,int b) { return a>b; } int dfs(int need,int now,int pos,int num) { if(flag) { return true; } if(num==t) { flag = true; return true; } for(int i = pos;i<t;i++) { if(!vis[i]&&a[i]+now<=need) { vis[i] = 1; if(now+a[i]==need) dfs(need,0,0,num+1); else dfs(need,a[i]+now,i+1,num+1); vis[i] = 0; if(now==0) return false; while(i+1<t&&a[i]==a[i+1]) i++; if(flag) return true; } } } int main() { while(cin>>t&&t!=0) { memset(vis,0,sizeof(vis)); memset(a,0,sizeof(a)); flag = false; sum = 0; maxx = 0; for(int i = 0;i<t;i++) { cin>>a[i]; sum+=a[i]; maxx = max(maxx,a[i]); } sort(a,a+t,cmp); if(maxx>sum-maxx) { cout<<sum<<endl; continue; } for(int i = maxx;i<=sum;i++) { if(sum%i==0) { dfs(i,0,0,0); if(flag) { cout<<i<<endl; break; } } } } }