这个dfs好一点,容易理解。
x代表当前到达的人,y代表已经选了多少个人,z代表这y个人的重量总和。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6;
int w[N];
int n, s, ans;
void dfs(int x, int y, int z) {
if(y == n / 2) {
ans = min(ans, abs(z * 2 - s));
return ;
}
if(x > n) return ;
dfs(x + 1, y + 1, z + w[x]);
dfs(x + 1, y, z);
}
int main() {
int t;
cin >> t;
while(t --) {
s = 0;
ans = 0x3f3f3f3f;
cin >> n;
for(int i = 1; i <= n; i ++) {
scanf("%d", &w[i]);
s += w[i];
}
dfs(1, 0, 0);
printf("%d\n", ans);
}
return 0;
}
//这是自己第一次写的
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e6;
int w[N];
int n, sum, ans, mid, res;
void dfs(int now, int tot) {
if(now > n && tot < n / 2)
return ;
if(tot == n / 2) {
if(abs(sum - mid / 2) < ans) {
ans = abs(sum - mid / 2);
res = abs((mid - sum) - sum);
}
return ;
}
dfs(now + 1, tot);
sum += w[now];
dfs(now + 1, tot + 1);
sum -= w[now];
}
int main() {
int t;
cin >> t;
while(t --) {
sum = mid = 0;
ans = 0x3f3f3f3f;
cin >> n;
for(int i = 1; i <= n; i ++) {
scanf("%d", &w[i]);
mid += w[i];
}
dfs(1, 0);
printf("%d\n", res);
}
return 0;
}