Sticks
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 110042 | Accepted: 25243 |
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
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
Sample Output
6 5
推荐指数:※※※※
来源:http://poj.org/problem?id=1011
经典的剪枝问题。
1.以棒子(箱子)的条数为主干,搜索。
2.去掉肯定不能装的,不能整除。
3.去掉相同长度的重复计算。
4.去掉相同状态下的重复计算。
#include <iostream> #include<string.h> #include<string> #include<sstream> #include<algorithm> using namespace std; int compare_int(const void *a,const void *b){ int *num_1=(int*)a; int *num_2=(int*)b; return (*num_2)-(*num_1); } int parts_num; int *parts; double capacity; bool *visit; bool dfs(int curr,int last_sum){//the capacity of current bin, the remain capacity of sum if(curr==capacity) return dfs(0,last_sum); if(last_sum==0) return true; int i; bool seen=false; for(i=0;i<=parts_num-1;i++){ if(false==visit[i]){ if(curr==0&&seen) return false; if(i-1>0&&parts[i]==parts[i-1]&&visit[i-1]==false) continue; if(curr+parts[i]<=capacity){ visit[i]=true; if(dfs(curr+parts[i],last_sum-parts[i])==false) visit[i]=false; else return true; } seen=true; } } if(i==parts_num) return false; } int main() { while(cin>>parts_num&&parts_num>0){ parts=new int[parts_num]; visit=new bool[parts_num]; int i,sum; for(i=0;i<=parts_num-1;i++){ cin>>parts[i]; } qsort(parts,parts_num,sizeof(int),compare_int); sum=0; for(i=0;i<=parts_num-1;i++) sum+=parts[i]; for(i=parts_num;i>=1;i--){ if(sum%i==0&&sum/i>=parts[0]){ memset(visit,0,parts_num*sizeof(bool)); capacity=sum/i; if(true==dfs(0,sum)){ cout<<capacity<<endl; break; } } } } return 0; }