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

链接

 

折半枚举的思想,主要讲暴力枚举,进行两次拆分,并且答案可以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;
}

 

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务