[YBT high-efficiency advanced] 1 basic algorithm/4 depth-first search/1 tug of war

[YBT high-efficiency advanced] 1 basic algorithm/4 depth-first search/1 tug of war

Memory limit: 256 MiB
Time limit: 1000 ms
standard input and output
Question type: Traditional
Evaluation method: Text comparison

Title description

In the ACM training team of Zhejiang Normal University, the team members usually have a heavy mental and labor force. In order to combine work and rest, our beloved Teacher Han prepared a tug-of-war competition to let the team members relax.

For the fairness of the tug-of-war competition, Mr. Han puts forward the following requirements:
1. The maximum number of people on both sides of the tug-of-war competition cannot differ by 1 11 .
2. Every team member has a weight, and we want to minimize the weight and difference between the two players.

Now has NNFor N players, Mr. Han would like you to help distribute them, and output the minimum value of the difference between the weights of the two sides after the distribution.

Input format

First enter TTT , means there isTTExample of group T.

Each example:

First enter the number of people NNN , occupies one line.

Followed by NNN number, which meansNNN person's weightW 1 − W n W_1-W_nW1Wn

Output format

For each sample output one line, an integer represents the absolute value of the difference between the weights of the two sides.

Sample

Sample input

1
3
55 50 100

Sample output

5

Data range and tips

对于 100% 的数据,有 1 < = T < = 50 , 2 < = N < = 20 , 30 < = W i < = 120 1<=T<=50,2<=N<=20,30<=W_i<=120 1<=T<=502<=N<=2030<=Wi<=120

Ideas

There are only two situations for each person on the left team and the right team.
Depth-first search O(2 N );

Code

#include<iostream>
#include<cmath>
using namespace std;
int n,sum,w[21],ans;
void DFS(int dep,int s,int rs)//dep当前人,s一边体重和,rs一边人数和 
{
    
    
	if(dep>n)
	{
    
    
		ans=min(ans,abs(sum-(s<<1)));
		return;
	}
	if(rs<(n+1)>>1)//可以加人 
		DFS(dep+1,s+w[dep],rs+1);
	if(dep-rs<=(n+1)>>1)
		DFS(dep+1,s,rs);
	return;
}
int main()
{
    
    
	int T,i;
	ios::sync_with_stdio(false);
	for(cin>>T;T--;)
	{
    
    
		for(cin>>n,sum=0,ans=100000000,i=1;i<=n;i++)
			cin>>w[i],sum+=w[i];
		DFS(1,0,0),cout<<ans<<endl;
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46975572/article/details/115144273