[Ybtoj Efficient Advanced 1.4] [Deep Search] Tug of War
topic
Problem-solving ideas
Deep search template questions,
take or not take two cases,
find all possibilities and take the smallest
Code
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int t,n,m,mi,ans,a[30];
void dfs(int x,int y,int sum)
{
if (y==m)
{
mi=min(abs(ans-sum-sum),mi);
return;
}
if (x>n) return;
dfs(x+1,y+1,sum+a[x]);
dfs(x+1,y,sum);
}
int main()
{
scanf("%d",&t);
for (int i=1;i<=t;i++)
{
mi=1000010;
ans=0;
scanf("%d",&n);
if (n%2)
m=n/2+1;
else m=n/2;
for (int j=1;j<=n;j++)
{
scanf("%d",&a[j]);
ans+=a[j];
}
dfs(1,0,0);
printf("%d\n",mi);
}
return 0;
}