牛牛的揹包問題 [折半枚舉]

鏈接

 

折半枚舉的思想,主要講暴力枚舉,進行兩次拆分,並且答案可以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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章