题目链接:http://www.spoj.com/problems/SUBSUMS/en/
SUBSUMS - Subset Sums
Given a sequence of N (1 ≤ N ≤ 34) numbers S1, ..., SN (-20,000,000 ≤ Si ≤ 20,000,000), determine how many subsets of S (including the empty one) have a sum between A and B (-500,000,000 ≤ A ≤ B ≤ 500,000,000), inclusive.
Input
The first line of standard input contains the three integers N, A, and B. The following N lines contain S1 through SN, in order.
Output
Print a single integer to standard output representing the number of subsets satisfying the above property. Note that the answer may overflow a 32-bit integer.
Example
Input: 3 -1 2 1 -2 3 Output: 5
The following 5 subsets have a sum between -1 and 2:
- 0 = 0 (the empty subset)
- 1 = 1
- 1 + (-2) = -1
- -2 + 3 = 1
- 1 + (-2) + 3 = 2
题意:输入n, a, b,然后n个整数,把n个数任意相加的和sum在 [a, b]区间的个数
解析:由于所有选择的情况比较多, 2^n必然超时,咱可以折半枚举,就是把所有数(n/2个)的情况放入一个数组,然后n - n/ 2的所有情况放入另外一个数组,把其中任意数组就行排序,然后二分答案累加即可,num1+num2 属于[a,b],那么枚举 num1(或者num2)在区间 [a-num1,b-num2] ([a-num1, b-num1])的个数,总体复杂度为2^(n/2)*log(2^(n/2))
代码:
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<map>
#include<cmath>
#include<string>
#define N 6000009
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
int num[36];
LL ff[N], f[N];
int main()
{
int n, a, b, cnt1, cnt2;
scanf("%d%d%d", &n, &a, &b);
for(int i = 0; i < n; i++) scanf("%d", &num[i]);
int k = 1<<(n/2), kk = n / 2;
cnt1 = cnt2 = 0;
for(int i = 0; i < k; i++)
{
LL sum = 0ll;
for(int j = 0; j < kk; j++)
{
if((i>>j)&1) sum += num[j];
}
f[cnt1++] = sum;
}
k = 1<<(n-kk);
for(int i = 0; i < k; i++)
{
LL sum = 0ll;
for(int j = 0; j < n - kk; j++)
{
if((i>>j)&1) sum += num[j + kk];
}
ff[cnt2++] = sum;
}
sort(f, f + cnt1);
LL ans = 0ll;
for(int i = 0; i < cnt2; i++)
{
int l = lower_bound(f, f + cnt1, a - ff[i]) - f;
int r = upper_bound(f, f + cnt1, b - ff[i]) - f;
ans += r - l;
}
cout << ans << endl;
return 0;
}