【dfs】【YBTOJ】拔河比赛

在这里插入图片描述


思路:

1.构造一个大小为n/2的组
2.两个组的体重之和是固定的,记所有人的体重和为S,则我们只用考虑构造出来的每一个的体重和尽可能接近S/2即可。

深搜实现


C o d e Code Code:

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


const int N = 30;
const int Max = 1321321311;
int t, n, w[N], ans, sum;
void dfs(int x, int y, int z)//dfs
{
    
    
	if(y == n / 2) {
    
    ans = min(ans, abs(sum - 2 * z)); return ;}
	if(x > n) return ;
	dfs(x + 1, y + 1, z + w[x]);
	dfs(x + 1, y, z);
}
int main ()
{
    
    
	scanf("%d", &t);
	while (t--)//边读入边运行
	{
    
    
		scanf("%d", &n); ans = Max; sum = 0;
		for(int i = 1; i <= n; i++) scanf("%d", &w[i]), sum += w[i];
		dfs(1, 0, 0);
		printf("%d\n", ans);
	}
    return 0;	
} 

猜你喜欢

转载自blog.csdn.net/hunkwu/article/details/114902294