题解看这里
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int t, maxp, w, dp[2005][2005], qaq[2005], haq, taq, ap, bp, as, bs, ans;
int main(){
cin>>t>>maxp>>w;
memset(dp, 128, sizeof(dp));
for(int i=1; i<=t; i++){
scanf("%d %d %d %d", &ap, &bp, &as, &bs);
for(int j=0; j<=as; j++)
dp[i][j] = -1 * j * ap;
for(int j=0; j<=maxp; j++)
dp[i][j] = max(dp[i][j], dp[i-1][j]);
if(i<=w) continue;
haq = 1; taq = 0;
for(int j=0; j<=maxp; j++){
while(haq<=taq && qaq[haq]<j-as) haq++;
while(haq<=taq && dp[i-w-1][qaq[taq]]+qaq[taq]*ap<=dp[i-w-1][j]+j*ap) taq--;
qaq[++taq] = j;
if(haq<=taq) dp[i][j] = max(dp[i][j], dp[i-w-1][qaq[haq]] + qaq[haq] * ap - j * ap);
}
haq = 1; taq = 0;
for(int j=maxp; j>=0; j--){
while(haq<=taq && qaq[haq]>j+bs) haq++;
while(haq<=taq && dp[i-w-1][qaq[taq]]+qaq[taq]*bp<=dp[i-w-1][j]+j*bp) taq--;
qaq[++taq] = j;
if(haq<=taq) dp[i][j] = max(dp[i][j], dp[i-w-1][qaq[haq]] + qaq[haq] * bp - j * bp);
}
}
for(int i=0; i<=maxp; i++)
ans = max(ans, dp[t][i]);
cout<<ans<<endl;
return 0;
}