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
额。。。。剪枝过后只要16ms ,我试过将其中一种注释掉,然后就TLE了…
这里的 stick 是指进行到第 stick 根木棒,cap 是指目前的长度,而 last 是指上一根拼凑的木棒。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<string>
#include<cmath>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<bitset>
#include<ctime>
#include<deque>
#include<stack>
#include<sstream>
typedef long long ll;
using namespace std;
typedef unsigned long long int ull;
#define maxn 100005
#define ms(x) memset(x,0,sizeof(x))
#define Inf 0x7fffffff
#define inf 0x3f3f3f3f
const long long int mod = 1e9 + 7;
#define pi acos(-1.0)
#define pii pair<int,int>
#define eps 1e-5
#define pll pair<ll,ll>
ll mul(ll a, ll b, ll mod) {
ll rt = 0;
while (b) {
if (b & 1)rt = (rt + a) % mod;
b = b / 2;
a = (a << 1) % mod;
}
return rt;
}
ll quickpow(ll a, ll b,ll mod) {
ll ans = 1, tmp = a;
while (b > 0) {
if (b % 2)ans = mul(ans, tmp, mod);
b = b / 2;
tmp = mul(tmp, tmp, mod);
}
return ans;
}
ll gcd(ll a, ll b) {
return b == 0 ? a : gcd(b, a%b);
}
int a[1000], vis[1000];
int n, len, cnt;
bool dfs(int stick, int cap, int last) {
if (stick > cnt)return true;
if (cap == len)return dfs(stick + 1, 0, 1);
int fail = 0;
for (int i = last; i <= n; i++) {
if (!vis[i] && a[i] + cap <= len && fail != a[i]) {
vis[i] = 1;
if (dfs(stick, cap + a[i], i+1))return true;
vis[i] = 0;
fail = a[i];
if (cap == 0 || cap + a[i] == len)return false;
}
}
return false;
}
bool cmp(int a, int b) {
return a > b;
}
int main() {
ios::sync_with_stdio(false);
while (cin >> n && n) {
int i, j;
int sum = 0;
int maxx = -inf;
for (i = 1; i <= n; i++) {
cin >> a[i];
sum += a[i];
maxx = max(maxx, a[i]);
}
sort(a + 1, a + 1 + n, cmp);
for (len = maxx; len <= sum; len++) {
if (sum%len == 0) {
cnt = sum / len;
ms(vis);
if (dfs(1, 0, 1))break;
}
}
cout << len << endl;
}
}