題意:zhx在比賽的時候有n道題目,第i道題目有一個分值vi,需要ti時間做完,而且必須在li或li之後完成。問zhx在獲得至少w分數的情況下需要的最少時間。
做法:類似於01揹包的做法,第i題可以選擇做或者不做。先對題目按照li-ti(即第i道題最早的開始時間)從小到大進行排序。然後遍歷,在此過程中維護一個top值,top指的是完成前I題之後儘可能遲的時間值。對於第i道題,li-ti到top的值纔有更新的可能,其他值都不可能被更新,所以dp的遞推過程也只會在這裏進行。
在以下代碼中,dp[i]代表在時間i結束後所能獲得的最大分數值。狀態轉移很簡單的,dp[j+vec[i].t]=max(dp[j+vec[i].t],dp[j]+vec[i].v);//vec是題目的數組名。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<climits>
using namespace std;
const int maxn=31;
struct pnt
{
int l,t,sta,v;
bool operator<(const pnt& b) const
{
return sta<b.sta;
}
}vec[maxn];
int dp[300005];
int main()
{
int n,w;
long long sum;
while(scanf("%d%d",&n,&w)!=EOF)
{
sum=0ll;
for(int i=0;i<n;i++)
{
scanf("%d%d%d",&vec[i].t,&vec[i].v,&vec[i].l);
vec[i].sta=vec[i].l-vec[i].t;
sum+=vec[i].v;
}
if(sum<w)
{
printf("zhx is naive!\n");
continue;
}
sort(vec,vec+n);
int top=0;
dp[0]=0;
for(int i=0;i<n;i++)
{
int ll=max(0,vec[i].sta);
int rr=max(vec[i].l,top+vec[i].t);
for(int j=top+1;j<=rr;j++)
dp[j]=dp[j-1];//先用上一道題的狀態來更新(假如第i道題不做)
for(int j=rr-vec[i].t;j>=ll;j--)//需要逆序進行,參照01揹包的一維做法
dp[j+vec[i].t]=max(dp[j+vec[i].t],dp[j]+vec[i].v);
top=rr;
}
int ans=0;
for(int i=0;i<=top;i++)
{
if(dp[i]>=w)
{
ans=i;
break;
}
}
printf("%d\n",ans);
}
}