>Link
ybtoj拔河比赛
>解题思路
一道非常典型的DFS,通过维护人数不超过总人数的一半来剪枝
为了方便,我DFS的时候用一个变量c来记录两队体重之差,左边队的就+,右边队的就-,最后取c的绝对值
>代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 30
#define inf 1 << 30
using namespace std;
int T, n, w[N], ans;
void dfs (int now, int cnt1, int cnt2, int c)
{
if (now == n + 1)
{
ans = min (ans, abs (c));
return;
}
if (cnt1 < n / 2 + (n & 1))
dfs (now + 1, cnt1 + 1, cnt2, c + w[now]);
if (cnt2 < n / 2 + (n & 1))
dfs (now + 1, cnt1, cnt2 + 1, c - w[now]);
}
void work ()
{
scanf ("%d", &n);
for (int i = 1; i <= n; i++) scanf ("%d", &w[i]);
ans = inf;
dfs (1, 0, 0, 0);
printf ("%d\n", ans);
}
int main()
{
scanf ("%d", &T);
while (T--) work ();
return 0;
}