This is the hard version of this problem. The only difference is the constraint on — the number of gifts in the offer. In this version: .
Vasya came to the store to buy goods for his friends for the New Year. It turned out that he was very lucky — today the offer " of goods for the price of one" is held in store.
Using this offer, Vasya can buy exactly of any goods, paying only for the most expensive of them. Vasya decided to take this opportunity and buy as many goods as possible for his friends with the money he has.
More formally, for each good, its price is determined by — the number of coins it costs. Initially, Vasya has coins. He wants to buy the maximum number of goods. Vasya can perform one of the following operations as many times as necessary:
Vasya can buy one good with the index if he currently has enough coins (i.e ). After buying this good, the number of Vasya’s coins will decrease by , (i.e it becomes ).
Vasya can buy a good with the index , and also choose exactly goods, the price of which does not exceed , if he currently has enough coins (i.e ). Thus, he buys all these goods, and his number of coins decreases by (i.e it becomes ).
Please note that each good can be bought no more than once.
For example, if the store now has goods worth , respectively, , and Vasya has coins, then he can buy goods. A good with the index will be bought by Vasya without using the offer and he will pay coins. Goods with the indices and Vasya will buy using the offer and he will pay coins. It can be proved that Vasya can not buy more goods with six coins.
Help Vasya to find out the maximum number of goods he can buy.
Input
The first line contains one integer () — the number of test cases in the test.
The next lines contain a description of test cases.
The first line of each test case contains three integers (, , ) — the number of goods in the store, the number of coins Vasya has and the number of goods that can be bought by the price of the most expensive of them.
The second line of each test case contains integers () — the prices of goods.
It is guaranteed that the sum of for all test cases does not exceed .
Output
For each test case in a separate line print one integer — the maximum number of goods that Vasya can buy.
这一题由于英语理解的原因,我将它看成了简单的贪心算法改了许多遍,还是
WA经过指点,这一题用dp;式子为dp[i]=dp[i-k]+a[i];在k个商品之前,未满足条件买的商品最优价格为各商品的累计价格,k个商品(包括k)第i个商品满足活动条件的总价格等于第i-k+1~i个商品的价格加上i-k前商品的总价格
#include
#include
#include
using namespace std;
int r[1000000],dp[1000000];
int main()
{
int y;
cin>>y;
while(y--){
int n,m,k;
scanf("%d%d%d",&n,&m,&k);
for(int i=1;i<=n;i++)
{
scanf("%d",&r[i]);
}
sort(r+1,r+n+1);
dp[1]=r[1];int y=0;
for(int i=1;i<=n;++i)
{
dp[i]=dp[i-1]+r[i];
if(i>=k)
dp[i]=dp[i-k]+r[i];
if(dp[i]<=m)
y=max(y,i);
}
printf("%d\n",y);
}
}