天天看點

K for the Price of One

​​B. K for the Price of One (Hard Version)​​

賽時失手推錯了規律...

這個題不是單調遞增的

但是它有一個規律:當買同樣多的東西時,優先買便宜的

是以我們可以求出買 i 個東西時最便宜的價格

sort(a+1,a+n+1);

for(int i=1;i<=k-1;++i)

dp[i]=a[i]+dp[i-1];

for(int i=k;i<=n;++i)

dp[i]=dp[i-k]+a[i];

因為考慮到 n 隻有2e5的範圍,是以把每一個\(dp[i]\)都周遊一遍找到最大值即可

代碼:

// Created by CAD on 2020/1/13.
#include <bits/stdc++.h>
#define ll long long
using namespace std;

const int maxn=2e5+5;
ll a[maxn];
ll dp[maxn];
ll n,p,k;
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int t;  cin>>t;
    while(t--)
    {
        cin>>n>>p>>k;
        for(int i=1;i<=n;++i)
            cin>>a[i];
        sort(a+1,a+n+1);
        for(int i=1;i<=k-1;++i)
            dp[i]=a[i]+dp[i-1];
        for(int i=k;i<=n;++i)
            dp[i]=dp[i-k]+a[i];
        int ans=0;
        for(int i=1;i<=n;++i)
            if(dp[i]<=p)
                ans=max(ans,i);
        cout<<ans<<endl;
    }
    return 0;
}