hdu-2639 Bone Collector II 背包第K优

本文介绍了一种解决背包问题的方法,通过维护一个大小不超过K的最大价值集合来优化解空间。这种方法利用了C++ STL中的set数据结构,并通过迭代物品和容量进行动态规划更新。

http://acm.hdu.edu.cn/showproblem.php?pid=2639

在背包的基础上维护一个size<=K的最大值集合,为什么维护K个就好了呢,因为如果当前状态有多余K个最优解,前K个就足够转移到下一状态并占满前K了,所以K个之后的都没必要维护。

#include <iostream>
#include <cstdio>
#include <vector>
#include <string>
#include <map>
#include <queue>
#include <set>
#define LL long long
using namespace std;
const LL N=1005;
set<LL> dp[N];
LL w[N];
LL v[N];
LL n,V,k;
int main()
{
    cin.sync_with_stdio(false);
    int t;
    cin>>t;
    while(t--)
    {
        cin>>n>>V>>k;
        for(int i=0; i<=V; i++)dp[i].clear(),dp[i].insert(0);
        for(int i=0; i<n; i++)
            cin>>v[i];
        for(int i=0; i<n; i++)
            cin>>w[i];
        for(int i=0; i<n; i++)
        {
            for(int j=V; j-w[i]>=0; j--)
            {
                int e=j-w[i];
                for(set<LL>::iterator it=dp[e].begin();it!=dp[e].end();it++)
                {
                    LL now=*it+v[i];
                    if(dp[j].size()==k)
                    {
                        if(now>*(dp[j].begin()))
                            dp[j].erase(*dp[j].begin()),dp[j].insert(now);
                    }
                    else dp[j].insert(now);
                }
            }
        }
        if(dp[V].size()<k)cout<<0<<endl;
        else
            cout<<*dp[V].begin()<<endl;
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/LukeStepByStep/p/7745026.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值