#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <list>
#include <deque>
#include <queue>
#include <cctype>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <limits>
#include <fstream>
using namespace std;
#define mem(A, X) memset(A, X, sizeof A)
#define pb(x) push_back(x)
#define mp(x,y) make_pair((x),(y))
#define all(x) x.begin(), x.end()
#define sz(x) (int)((x).size())
#define rep(i,l,u) for(int (i)=(int)(l);(i)<(int)(u);++(i))
#define Rep(i,l,u) for(int (i)=(int)(l);(i)<=(int)(u);++(i))
#define min3(a,b,c) min(a,min(b,c))
#define max3(a,b,c) max(a,max(b,c))
#define dbg(a) cout << a << endl;
#define fi first
#define se second
typedef long long int64;
int gcd(const int64 &a, const int64 &b) {return b == 0 ? a : gcd(b, a % b);}
int64 int64pow(int64 a, int64 b){if(b == 0) return 1;int64 t = int64pow(a, b / 2);if(b % 2) return t * t * a;return t * t;}
const int inf = 1 << 30;
const double eps = 1e-8;
const double pi = acos(-1.0);
const int MAX_N = 1005;
int arr[MAX_N], sum, n, ans, MAX;
bool visit[MAX_N];
bool comp(const int &a, const int &b){
return a > b;
}
bool dfs(int *arr, bool *visit, int len, int ans, int s, int num)
{
if (num == n)
return true;
int sample = -1;
rep(i, s, n) {
if (visit[i] || arr[i] == sample)//剪枝3:等长的木棒只搜索一次
continue;
visit[i] = true;
if (len + arr[i] < ans) {
if (dfs(arr, visit, len + arr[i], ans, i, num + 1))
return true;
else
sample = arr[i];
}
else if (len + arr[i] == ans) {
if (dfs(arr, visit, 0, ans, 0, num + 1))
return true;
else
sample = arr[i];
}
visit[i] = false;
if (len == 0)//剪枝4:构建新棒时,对于新棒的第一根棒子,在搜索完所有棒子后都无法组合
break; //则说明该棒子无法在当前组合方式下组合,不用往下搜索(往下搜索会令该棒子被舍弃),直接返回上一层
}
return false;
}
void solve()
{
mem(visit, 0);
sum = ans = 0;
rep(i, 0, n) {
scanf("%d", &arr[i]);
sum += arr[i];
}
sort(arr, arr + n, comp);
MAX = arr[0];
Rep(i, 1, sum) { //剪枝1:答案必然在[1, sum]内
if ((sum % i == 0) && dfs(arr, visit, 0, i, 0, 0)) {//剪枝2: 答案必须是sum的约数
ans = i;
break;
}
}
printf("%d\n", ans);
}
int main()
{
while (cin >> n && n) {
solve();
}
}
POJ1011 Sticks
最新推荐文章于 2021-02-18 11:21:18 发布