1. 程式人生 > >poj1011——Sticks(dfs+剪枝)

poj1011——Sticks(dfs+剪枝)

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

給出一些小木棒,能組合成長度相同的一組木棒,求這組木棒的最小長度
沒想到這道題也能用搜索,不過要剪掉很多情況才不會超時

#include <iostream>
#include <cstring>
#include <string>
#include <vector>
#include <queue>
#include <cstdio>
#include <set>
#include <math.h>
#include <algorithm> #include <queue> #include <iomanip> #include <map> #define INF 0x3f3f3f3f #define MAXN 1005 #define Mod 99999999 using namespace std; int stick[100],vis[100],len,n; bool cmp(int a,int b) { return a>b; } bool dfs(int i,int l,int r) { if(l==0) { r-=len; if(r==0) return true; int i; for(i=0; vis[i]; ++i); vis[i]=1; if(dfs(i+1,len-stick[i],r)) return true; vis[i]=0; r+=len; } else { for(int j=i; j<n; ++j) { if(j>0&&(stick[j]==stick[j-1]&&!vis[j-1])) //上一個相同長度的沒有被用上,這一個肯定也不會用 continue; if(!vis[j]&&l>=stick[j]) { l-=stick[j]; vis[j]=1; if(dfs(j,l,r)) return true; l+=stick[j]; vis[j]=0; } } } return false; } int main() { while(~scanf("%d",&n)&&n) { memset(vis,0,sizeof(vis)); int sum=0; for(int i=0; i<n; ++i) { scanf("%d",&stick[i]); sum+=stick[i]; } sort(stick,stick+n,cmp); int flag=0; for(len=stick[0]; len<=sum; ++len) { if(sum%len==0) { if(dfs(0,len,sum)) { printf("%d\n",len); flag=1; break; } } } if(!flag) printf("%d\n",sum); } return 0; }