题解 P1537 【弹珠】

· · 题解

其实这个直接bitset+dp就行啦。

比较朴素的背包转移方程就是:对于第i个物品,枚举所有可能得到的价值j来进行转移:

dp(i,j) += dp(i-1,j-v_i),v_i\leq j\leq k

然后我们用一个bitset来储存阶段为i-1所有的状态,如果价值有一个价值x,那么x这个位置就为1。

之后转移的时候就dp |= dp<<i就行了,这里的|其实就代表了选与不选两种情况。

这样复杂度因为bitset还有所优化,多除以了一个32 or 64。 代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 120005;
bitset <N> dp;
int a[10] ;
int main() {
    ios::sync_with_stdio(false); cin.tie(0);
    int Case = 0;
    while(1) {
        Case++;
        int sum = 0;
        for(int i = 1; i <= 6; i++) cin >> a[i], sum += i * a[i] ;
        if(sum == 0) break ;
        cout << "Collection #" << Case << ":" << '\n';
        if(sum & 1) {
            cout << "Can't be divided." << '\n' << '\n';
            continue ;
        }
        dp.reset() ;
        dp.set(0) ;
        int ok = 0;
        for(int i = 1; i <= 6; i++) {
            for(int j = 1; j <= a[i]; j++) {
                dp |= (dp << i);
                if(dp[sum / 2]) ok = 1;
            }
        }
        if(ok) cout << "Can be divided." << '\n';
        else cout << "Can't be divided." <<'\n';
        cout << '\n';
    }
    return 0;
}