Codeforces 1282B2 K for the Price of One (Hard Version)

题目链接:

1282B2 K for the Price of One (Hard Version)

思路:

首先排序,再设dp[i]是index从0买到i为止的最小开销,然后以贪心思想递推;
最后求满足dp[i]<=p的最大i即可

代码:

#include<bits/stdc++.h>
using namespace std;
typedef pair<int,int> P;
typedef long long LL;
#define fi first
#define sc second
#define pb(a) push_back(a)
#define mp(a,b) make_pair(a,b)
#define pt(a) cerr<<a<<"---\n"
#define rp(i,n) for(int i=0;i<n;i++)
#define rpn(i,n) for(int i=1;i<=n;i++)
int main(){
	ios::sync_with_stdio(false); cin.tie(nullptr);
	int t; cin>>t;
	while(t--){
		int n,p,k; cin>>n>>p>>k;
		vector<int> a(n);
		rp(i,n) cin>>a[i];
		sort(a.begin(),a.end());
		vector<int> dp(n);
		rp(i,n){
			if(i>=k-1) dp[i]=(i>=k?dp[i-k]:0)+a[i];
			else dp[i]=(i?dp[i-1]:0)+a[i];
		}
		int ans=-1;
		rp(i,n) if(dp[i]<=p) ans=i;
		cout<<ans+1<<'\n';
	}
	return 0;
}
posted @ 2019-12-25 19:10  YuhanのBlog  阅读(148)  评论(0编辑  收藏  举报