1. 程式人生 > >POJ 1011 Sticks 【DFS 剪枝】

POJ 1011 Sticks 【DFS 剪枝】

解題思路 pro first mit contain earch smallest miss set

題目鏈接:http://poj.org/problem?id=1011

Sticks

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 154895 Accepted: 37034

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

Source

Central Europe 1995

題意概括:

George這家夥一開始把幾條長度一樣的木棍切成了好多小木棍,後來忘記原來有幾條長度一樣的木棍了,所以請我們幫幫忙把這些小木棍拼成盡可能長的長度相同的長木棍,輸出長度。

解題思路:

先根據小木棍的長度降序排序

枚舉木棍長度(可以整除小木棍總長度),DFS湊這些木棍。

剪枝:如果當前這條小木棍不能湊則這一類小木棍都湊不了(這也是要排序的原因)

AC code:

 1 ///poj 1011 dfs
 2 #include <cstdio>
 3
#include <iostream> 4 #include <algorithm> 5 #include <cstring> 6 #include <cmath> 7 #define INF 0x3f3f3f3f 8 using namespace std; 9 10 const int MAXN = 70; 11 bool vis[MAXN]; 12 int sticks[MAXN]; 13 int N, sum, len; 14 bool flag; 15 16 bool cmp(int x, int y) 17 { 18 return x>y; 19 } 20 21 void dfs(int dep, int now_len, int st) ///當前已經使用的木條數目,當前木條的長度, 需要處理的木條的下標 22 { 23 if(flag) return; 24 if(now_len == 0) ///找木棍頭 25 { 26 int k = 0; 27 while(vis[k]) k++; 28 vis[k] = true; 29 dfs(dep+1, sticks[k], k+1); 30 vis[k] = false; 31 return; 32 } 33 if(now_len == len) 34 { 35 if(dep == N) flag = true; ///找到滿足條件的len了 36 else dfs(dep, 0, 0); ///沒有用完,開始湊新的一根長度為len的木棍 37 return; 38 } 39 for(int i = st; i < N; i++) 40 { 41 if(!vis[i] && now_len + sticks[i] <= len) 42 { 43 if(!vis[i-1] && (sticks[i-1] == sticks[i])) continue; 44 vis[i] = true; 45 dfs(dep+1, now_len+sticks[i], i+1); 46 if(flag) return; 47 vis[i] = false; 48 } 49 } 50 } 51 52 void init() 53 { 54 memset(vis, 0, sizeof(vis)); 55 flag = false; 56 sum = 0; 57 } 58 59 int main() 60 { 61 while(~scanf("%d", &N) && N ) 62 { 63 init(); 64 for(int i = 0; i < N; i++) 65 { 66 scanf("%d", &sticks[i]); 67 sum+=sticks[i]; 68 } 69 sort(sticks, sticks+N, cmp); 70 for(len = sticks[0]; len < sum; len++) 71 { 72 if(sum%len==0) 73 { 74 dfs(0, 0, 0); 75 if(flag) break; 76 } 77 } 78 printf("%d\n", len); 79 } 80 return 0; 81 }

POJ 1011 Sticks 【DFS 剪枝】