[Ybtoj Chapter 4 Example 1] Tug of War [Deep Search]

Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here
Insert picture description here


Problem solving ideas

This is a very simple deep search.

According to the question, each group has at most n 2 \frac{n}{2}2nIndividuals, for each person, there are only two situations of choosing and not choosing.
The sum of the cumulative selections is subtracted by the sum of all people to get the weight of the other pair, just take the absolute value.


Code

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

int t,n,a[50],lyx,ans;

void dfs(int dep,int x,int s){
    
    
	if(x==n/2)
	{
    
    
		ans=min(ans,abs(lyx-s*2));
		return;
	}
	if(dep>n)return;
	dfs(dep+1,x+1,s+a[dep]);
	dfs(dep+1,x,s);
}
int main(){
    
    
	scanf("%d",&t);
	while(t--)
	{
    
    
		ans=2147483600; 
		lyx=0;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)
		{
    
    
			scanf("%d",&a[i]);
			lyx+=a[i];
		}
		dfs(1,0,0);
		printf("%d\n",ans);
	}
	
} 

Guess you like

Origin blog.csdn.net/kejin2019/article/details/112390544