TLE: poj 1011 Sticks

Ozy的方法(dfs):

 1 # include <stdio.h>
2 # include <string.h>
3
4 int f[51];
5 int ok;
6 int length;
7
8 void dfs(int cnt, int len, int cur)
9 {
10 int j;
11
12 if (cnt == 0) {ok = 1; return;}
13
14 --f[cur];
15
16 len -= cur;
17 if (len != 0)
18 {
19 j = len<cur ? len:cur;
20 for (; j > 0; --j)
21 if (f[j]) dfs(cnt, len, j);
22 }
23 else
24 {
25 for (j = 50; !f[j] ; ) --j;
26 dfs(cnt-1, length, j);
27 }
28
29 ++f[cur];
30 }
31
32 int main()
33 {
34 int i, n, x, max, sum;
35
36 while (1)
37 {
38 scanf("%d", &n);
39 if (n == 0) break;
40
41 ok = 0;
42 sum = max = 0;
43 memset(f, 0, sizeof(f));
44
45 for (i = 1; i <= n; ++i)
46 {
47 scanf("%d", &x);
48 ++f[x];
49 sum += x;
50 if (x > max) max = x;
51 }
52
53 for (length = max; !ok ; ++length)
54 if (sum%length == 0) dfs(sum/length, length, max);
55
56 printf("%d\n", length-1);
57 }
58
59 return 0;
60 }



你可能感兴趣的:(poj)