USACO Subset Sums

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
ID: wcr19961
PROG: subset
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = (1 << 20) + 10;
int sum[maxn];

int main() {
freopen("subset.in", "r", stdin);
freopen("subset.out", "w", stdout);
int n;
scanf("%d", &n);
int aim = (n * (n + 1)) >> 1;
if (aim & 1) {
puts("0");
return 0;
}
aim >>= 1;
int p = (n + 1) >> 1, S = 1 << p, num = S;
for (int i = 0; i < S; ++i) {
for (int j = 0; j < p; ++j) {
if (i & (1 << j)) {
sum[i] += j + 1;
}
}
}
sort(sum, sum + num);
p = n - p, S = 1 << p;
LL ans = 0;
for (int i = 0; i < S; ++i) {
int tmp = 0;
for (int j = 0; j < p; ++j) {
if (i & (1 << j)) {
tmp += n - j;
}
}
ans += int(upper_bound(sum, sum + num, aim - tmp) - lower_bound(sum, sum + num, aim - tmp));
}
printf("%d\n", int(ans >> 1));
return 0;
}