算法
从题目看显然是背包dp(背包dp可以看 P1802 了解),首先想到定义 表示前 个宝石,免费了 个宝石,总花费为 的最大收益。但是时间复杂度 ,会TLE。于是想到对于每个宝石,若宝石没有被买得,则免费获得的宝石一定是这些宝石之中 的前 大值和,可以考虑优先队列维护。被选择的宝石部分使用dp,dp方程改为 表示前 个宝石,总花费为 的最大价值,时间复杂度 。
具体见代码
AC code
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
int n,w,k,f[10005],s[10005],nowsum;
inline int read(){
int ret=0,f=1;char ch=getchar();
while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
while (ch>='0'&&ch<='9') ret=ret*10+ch-'0',ch=getchar();
return ret*f;
}
struct Node{
int w,v;
bool operator<(const Node b)const{
return w<b.w||(w==b.w&&v>b.v); //跑dp构造时按照花费排序
}
}lst[5005];
struct vp{
int w,v;
bool operator>(const vp b)const{
return v>b.v||(v==b.v&&w<b.w); //按照v维护前k大
}
vp(Node b){w=b.w,v=b.v;}
};
priority_queue<vp,vector<vp>,greater<vp>> q;
signed main(){
n=read(),w=read(),k=read();
for(int i=1;i<=n;i++){
int w=read(),v=read();
lst[i]={w,v};
}
sort(lst+1,lst+1+n);
for(int i=1;i<=n;i++)
for(int j=w;j>=0;j--)
if(j>=lst[i].w) s[i]=max(s[i],f[j]=max(f[j],f[j-lst[i].w]+lst[i].v)); //维护选取前 i 个宝石最优
int ans=0;
for(int i=n;i>=1;i--){
ans=max(nowsum+s[i],ans); //加上优先队列维护的k大值的和,统计答案
q.push(lst[i]);
nowsum+=lst[i].v; //维护优先队列内存放的数值的总和
if(q.size()>k){
nowsum-=q.top().v;
q.pop();
}
}
cout<<ans;
return 0;
}