分组背包(p1537)

文章讨论了如何使用bitset数据结构优化解决01背包问题,对比了朴素的01背包算法并展示了bitset在处理具有特定条件的背包问题中的效率提升。
摘要由CSDN通过智能技术生成

题目链接

bitset优化:过了!!!

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 120005; //最大价值和 
bitset <N> dp;
//如果价值有一个价值x,那么x这个位置就为1。 
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) ;		//将 dp 的第 0 位(也就是和值为 0 的情况)设置为 1。
        int ok = 0;
        for(int i = 1; i <= 6; i++) {
            for(int j = 1; j <= a[i]; j++) {
                dp |= (dp << i);			//转化成位数,价值为i相当于位数左移i位上为1; 
                if(dp[sum / 2]) ok = 1;
            }
        }
        if(ok) cout << "Can be divided." << '\n';
        else cout << "Can't be divided." <<'\n';
        cout << '\n';
    }
    return 0;
}

题目链接

朴素做法,看成01背包。。。tle一个测试点

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 120005; //最大价值和 
int dp[N];

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[0]=1;
        int ok = 0;
        for(int i = 1; i <= 6; i++) {
            for(int j = 0; j <= a[i]; j++) {
            	for(int k=sum;k>=j*i;k--)
            	{
            		dp[k]|=dp[k-j*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;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值