题目链接:
思路:搜索,构造一个二叉树,左子树是不要这块西瓜,右子树是要这块西瓜,然后相当于枚举完了
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
const int maxn = 22;
int judge[maxn]; //判断该西瓜用过没有
int fru[maxn]; //存储西瓜重量
int num,alw,c_w,ans,temp; //代表num块西瓜,总质量是alw,小C分到的重量是从c_w,ans是当前搜索状态下的差值
void dfs(int i);
int main()
{
while(~scanf("%d",&num))
{
alw=0; //一开始西瓜总量是n
for(int i=1;i<=maxn;i++)
{
judge[i]=1;
}
for(int i=1;i<=num;++i)
{
scanf("%d",&fru[i]); //用fru存储西瓜重量
alw+=fru[i]; //先求出西瓜总质量
}
c_w=0; //小C一开始分到的西瓜质量是0
ans=alw; //差值假设是总重量
dfs(1); //从第一块西瓜开始搜索
printf("%d\n",ans);
}
return 0;
}
void dfs(int ithwaterm)
{
if(ithwaterm>num){ //如果搜到第num+1块西瓜,代表结束
temp=abs(alw-2*c_w);
if(temp<ans)
{
ans=temp;
}
return ;
}
dfs(ithwaterm+1); //不要这块西瓜
c_w+=fru[ithwaterm]; //要这块西瓜
dfs(ithwaterm+1);
c_w-=fru[ithwaterm]; //恢复
}