题目描述
部门准备举办一场王者荣耀表演赛,有 10 名游戏爱好者参与,
分为两队,每队 5 人。
每位参与者都有一个评分,代表着他的游戏水平。
为了表演赛尽可能精彩,我们需要把 10 名参赛者分为实力尽量相近的两队。
一队的实力可以表示为这一队 5 名队员的评分总和。
现在给你 10 名参与者的游戏水平评分,请你根据上述要求分队最后输出这两组的实力差绝对值。
例: 10 名参赛者的评分分别为 5 1 8 3 4 6 7 10 9 2,分组为 (1 3 5 8 10) (2 4 6 7 9),
两组实力差最小,差值为 1。有多种分法,但实力差的绝对值最小为 1。
输入描述
10 个整数,表示 10 名参与者的游戏水平评分。范围在[1,10000]之间
输出描述
1 个整数,表示分组后两组实力差绝对值的最小值。
示例一
输入
1 2 3 4 5 6 7 8 9 10
输出
1
说明
10 名队员分成两组,两组实力差绝对值最小为 1。
考点
排列组合
解题思路
1.采用递归的方式,通过枚举加入和不加入该参与者的评分,在每组的人数达到
5人时,计算两组实力差的绝对值,一直更新取最小差值。
代码
c++
#include <bits/stdc++.h>
using namespace std;
int sum=0;
int res=INT32_MAX;
void dfs(vector<int> vec, int ind, int cnt, int total) {
if(cnt==5) {
int other=sum-total;
res=min(abs(total-other), res);
return;
}
if(ind==10) {
return;
}
dfs(vec, ind+1, cnt+1, total+vec[ind]);
dfs(vec, ind+1, cnt, total);
}
int main() {
int tmp;
vector<int> vec;
while(cin>>tmp){
vec.push_back(tmp);
sum+=tmp;
if(cin.get()=='\n') break;
}
dfs(vec, 0, 0, 0);
cout<<res<<endl;
system("pause");
return 0;
}
python
vec=list(map(int,input().split()))
vec.sort() #升序排序,便于进行