感觉思路没问题,应该是细节,但是没调出来
#include<bits/stdc++.h>
// #define int long long
using namespace std;
template <typename T>
void read(T &x)
{
T f = 1,res = 0;
char ch = getchar();
while(!isdigit(ch)){if(ch == '-') f = -1;ch = getchar();}
while(isdigit(ch)){res = (res << 1) + (res << 3) + (ch ^ 48);ch = getchar();}
x = res * f;
}
const int MAXN = 5e3 + 10,inf = 0x3f3f3f3f;
int K,V,n,valx[MAXN],valy[MAXN],dp[MAXN][MAXN],v[MAXN],w[MAXN];
signed main()
{
read(K),read(V),read(n);
for(int i = 1;i <= n;i ++)
read(v[i]),read(w[i]);
for(int i = 1;i <= n;i ++)
{
for(int j = V;j >= v[i];j --)
{
for(int k = 1;k <= K;k ++)
{
valx[k] = dp[k][j - v[i]] + w[i];
valy[k] = dp[k][j];
}
valx[K + 1] = -inf,valy[K + 1] = -inf;
int posx = 1,posy = 1,pos = 1;
while(pos <= K && (valx[posx] != -inf || valy[posy] != -inf))
{
if(valx[posx] > valy[posy])
dp[pos][j] = valx[posx ++];
else
dp[pos][j] = valy[posy ++];
if(dp[pos][j] != dp[pos - 1][j]) pos ++;
}
}
}
int Answer = 0;
for(int i = 1;i <= K;i ++)
Answer += dp[i][V];
printf("%d\n",Answer);
return 0;
}