牛牛的背包问题 [折半枚举]

链接

 

折半枚举的思想,主要讲暴力枚举,进行两次拆分,并且答案可以sort后寻找匹配方案的情况下,使用折半枚举

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
ll n,w,v[50];
vector<int> ans1,ans2;
int main(void){
    cin >>n >>w;
    for(int i=0;i<n;i++)    cin >> v[i];
    int n1=n/2;
    int n2=n-n1;
    for(int i=0;i<=(1<<n1)-1;i++){
        ll tot=0;
        for(int j=0;j<=n1-1;j++){
            if(i&(1<<j))    tot+=v[j];
        }
        if(tot<=w)  ans1.push_back(tot);
    }
    for(int i=0;i<=(1<<n2)-1;i++){
        ll tot=0;
        for(int j=0;j<=n2-1;j++){
            if(i&(1<<j))    tot+=v[j+n1];
        }
        if(tot<=w)  ans2.push_back(tot);
    }
    sort(ans1.begin(),ans1.end());
//    for(auto num : ans1)    cout << num <<" ";
//    cout << endl;
    sort(ans2.begin(),ans2.end());
//    for(auto num : ans2)    cout << num <<" ";
//    cout << endl;
    ll ans=0;
    for(auto a : ans1){
        auto pos=upper_bound(ans2.begin(),ans2.end(),w-a)-ans2.begin();
//        cout <<"pos= " << pos << endl;
        pos--;
        if(pos>=0)   ans+=pos+1;
    }
    cout << ans << endl;

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值