Anhao Li
[AGC020C] Median SumBlur image

Problem#

Given a multiset of nn integers a1,2,3,...,na_{1,2,3,...,n}, find the median of the sums of its non-empty subsets.

Solution#

Enumerating every subset is hopeless — there are 2N2^N of them.

So let’s look at the quantity we are asked for instead.

There is an easy observation. Let TT be the full set and let SUMSUM be the sum of all the numbers. For a subset SS with sum sumsum, its complement TST-S exists and has sum SUMsumSUM - sum. Every subset therefore has a symmetric partner.

So the median over all subsets must be the first attainable value that is at least SUM2\frac{SUM}{2}.

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
[AGC020C] Median Sum
https://www.lomit.top/en/blog/icpc/agc020c-median-sum
Author Anhao Li
Published at November 11, 2024