![[AGC020C] Median Sum](/_astro/1.DQtKcykb_ZdEzKy.webp)

[AGC020C] Median Sum
Finding the median of all non-empty subset sums with a bitset knapsack.
Problem#
Given a multiset of integers , find the median of the sums of its non-empty subsets.
Solution#
Enumerating every subset is hopeless — there are of them.
So let’s look at the quantity we are asked for instead.
There is an easy observation. Let be the full set and let be the sum of all the numbers. For a subset with sum , its complement exists and has sum . Every subset therefore has a symmetric partner.
So the median over all subsets must be the first attainable value that is at least .
Which means we just run a knapsack, using a bitset to speed up the transition.
#include<bits/stdc++.h>
#define N 4000050
using namespace std;
int n;
bitset<N> f;
int main() {
scanf("%d", &n);
f[0] = 1; int s = 0;
for(int i = 1; i <= n; i ++) {
int x;
scanf("%d", &x);
f |= f << x; s += x;
}
for(int i = (s + 1) / 2; i <= s; i ++) if(f[i]) {printf("%d", i); return 0;}
return 0;
}cpp