Question: You want to buy gifts for your friends. You now have two purchase methods
. The first is to buy an item at the price of a[i].
The second is to choose k items and spend this k The maximum price of the items to get these k items.
You now have the amount of money p. Ask how many gifts you can buy at most.
If you want to get more gifts with less money then I will definitely use my right To get k items,
order the item prices
dp[i] array to record the cost of buying i items
without using the right to buy
dp[i] = dp[i-1] + a[i];
use the right k Pack together
dp[i] = dp[ik] + a[i]; the
state transition equation is obtained:
dp[i] = min(dp[i-1]+a[i],dp[ik]+a[i] );
Then after traversing, find out what is the largest i that can be bought by p money and output i
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
typedef long long ll;
const int MAXN = 2e5+7;
int a[MAXN],dp[MAXN];
int main()
{
int t;
cin>>t;
while(t--)
{
int n,p,k;
scanf("%d%d%d",&n,&p,&k);
for(int i = 1;i <= n;i ++){
scanf("%d",&a[i]);
}
sort(a+1,a+1+n);
for(int i = 1;i <= n;i ++)
{
dp[i] = dp[i-1]+a[i];
if(i >= k)
{
dp[i] = min(dp[i],dp[i-k]+a[i]);
}
}
int ans = 0;
for(int i = 1;i <= n;i ++)
{
if(p >= dp[i])
{
ans = max(ans,i);
}
}
printf("%d\n",ans);
}
return 0;
}