Sticks 这道题放了好才时间了,今天打算做下来,无奈还是不行,一直TLE,甚至后面照别人的代码往上加剪枝,减到最后还是TLE,实在没招了。 这是TLE的代码: #include <iostream> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <string> #include <cstdio> #include <climits> #include <queue> using namespace std; int data[70]; int st[70]; int len, sum, elen; bool yes; bool cmp(int a, int b) { return a > b; } bool dfs(int in, int coml, int comn) { if (coml == elen) { if (comn == sum/elen -2) { return true; } for (in = 0; st[in] != 0; in++); st[in] = true; if (dfs(in+1, data[in], comn+1)) return true; st[in] = false; return false; } else { if (in >= len-1) return false; for (int i = in; i < len; i++) { if (!st[i] && coml + data[i] <= sum) { if (data[i] == data[i-1] && !st[i]) continue; st[i] = true; if (dfs(i+1, coml + data[i], comn)) return true; st[i] = false; } } return false; } } int main() { while (scanf("%d", &len), len) { sum = 0; for (int i=0; i < len; i++) { scanf("%d", data+i); sum += data[i]; } sort(data, data+len, cmp); yes = false; memset(st, 0, sizeof(st)); for (elen = data[0]; elen <= sum/2; elen++) { if (sum % elen != 0) continue; st[0] = true; if (yes = dfs(1, data[0], 0)) { printf("%d/n", elen); break; } st[0] = false; } if (!yes) printf("1/n"); } return 0; } 这是AC的: #include <iostream> #include <algorithm> #include <cstring> using namespace std; int sticks[64], n, len, num; bool used[64]; bool compare(int a, int b) { return a > b; } bool dfs(int cur, int left, int level) { if (left == 0) { if (level == num - 2) return true; for (cur = 0; used[cur]; cur++); used[cur] = true; if (dfs(cur + 1, len - sticks[cur], level + 1)) return true; used[cur] = false; return false; } else { if (cur >= n - 1) return false; for (int i = cur; i < n; i++) { if (used[i]) continue; if ((sticks[i] == sticks[i - 1]) && !used[i - 1]) continue; if (sticks[i] > left) continue; used[i] = true; if (dfs(i, left - sticks[i], level)) return true; used[i] = false; } return false; } } int main() { while (scanf("%d", &n), n) { int sum = 0; memset(used, 0, sizeof(used)); for (int i = 0; i < n; i++) { scanf("%d", sticks+i); sum += sticks[i]; } sort(sticks, sticks + n, compare); bool end = false; for (len = sticks[0]; len <= sum / 2; len++) { if (sum % len == 0) { used[0] = true; num = sum / len; if (dfs(0, len - sticks[0], 0)) { end = true; printf("%d/n", len); break; } used[0] = false; } } if (!end) printf("%d/n", sum); } return 0; } 以后要多练习剪枝啊。