题解 | #货船#

货船

https://ac.nowcoder.com/acm/problem/236172

使用二进制运算去优化01背包的循环过程可以。
可以使用二进制去优化01背包的循环过程原因:在背包循环里面其实是针对于某一个物品判断如果他自身不取或者取能不能有一种是可以满足条件的。那么不取显而易见就是上一层循环的结果直接继承下来,取呢?取就得减去这个物品本身的重量,那么这个过程其实和序列整体左移是一样的效果。那么直接左移重量个位数,然后位或运算就可以实现这两个要求。
#include "bits/stdc++.h"
#define IOS ios::sync_with_stdio(false),cin.tie(nullptr),cout.tie(nullptr)
using namespace std;
using ll=long long;
const int N = 1e5+10;
ll n,A,w;
bitset<N> bits;
int main(){
    IOS;
    cin>>n>>A;
    bits.set(0,1);
    for (int i=1;i<=n;i++){
        cin>>w;
        bits|=(bits<<w);
    }
    for (int i=A;i>=0;i--){
        if (bits[i]){
            cout<<i;
            break;
        }
    }
    return 0;
}


全部评论

相关推荐

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