SPOJ SUBSUMS - Subset Sums

题目链接: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;
}













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值