Codeforces 985C (贪心)
题面:
You have m = n·k wooden staves. The i-th stave has length ai. You have to assemble n barrels consisting of k staves each, you can use any k staves to construct a barrel. Each stave must belong to exactly one barrel.
Let volume vj of barrel j be equal to the length of the minimal stave in it.
You want to assemble exactly n barrels with the maximal total sum of volumes. But you have to make them equal enough, so a difference between volumes of any pair of the resulting barrels must not exceed l, i.e. |vx - vy| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.
Print maximal total sum of volumes of equal enough barrels or 0 if it's impossible to satisfy the condition above.
The first line contains three space-separated integers n, k and l (1 ≤ n, k ≤ 105, 1 ≤ n·k ≤ 105, 0 ≤ l ≤ 109).
The second line contains m = n·k space-separated integers a1, a2, ..., am (1 ≤ ai ≤ 109) — lengths of staves.
Print single integer — maximal total sum of the volumes of barrels or 0 if it's impossible to construct exactly n barrels satisfying the condition |vx - vy| ≤ l for any 1 ≤ x ≤ n and 1 ≤ y ≤ n.
4 2 1 2 2 1 2 3 2 2 3
7
2 1 0 10 10
20
1 2 1 5 2
2
3 2 1 1 2 3 4 5 6
0
In the first example you can form the following barrels: [1, 2], [2, 2], [2, 3], [2, 3].
In the second example you can form the following barrels: [10], [10].
In the third example you can form the following barrels: [2, 5].
In the fourth example difference between volumes of barrels in any partition is at least 2 so it is impossible to make barrels equal enough.
题目意思:
你有n个桶,每个桶由k块木板组成,一个木桶的容水量为最短的木板的长度。先给你n*k块木板的长度,问你在两两木桶的容积不超过l的条件下,组成n个桶能获得的最大容积和是多少。
题目分析:
根据木桶原理我们可以得知,木桶的容积与长度很大的木板没有任何关系。因此我们先将所有木桶的长度排序。因为要组成n个木桶,(在最差的情况下,我们的策略是第1个木板跟第n*k个木板组合,第2个模板和第n*k-1个木板结合)。因此,首先我们先需要判断第n块木板和第一块木板的长度。倘若这两块木板的差值已经是大于l了,则表明必定无法构成n个桶,故输出0。
而倘若上述两块小于等于l,则此时需要采用贪心的策略。因为我们需要得到最大的容积,因此,我们需要尽可能贪心地将上界提高。因此我们需要在所有木板中找到第一个与第一块木板长度差大于l的木板,然后在计算容积的过程中,尽可能地让长度短的木板优先形成木桶,进而使得长度大的木板对结果有贡献,从而使得答案的结果最大。
代码:
#include <bits/stdc++.h>
#define maxn 100005
using namespace std;
typedef long long ll;
ll a[maxn];
int main()
{
ll n,k,l;
cin>>n>>k>>l;
for(int i=0;i<n*k;i++){
cin>>a[i];
}
sort(a,a+n*k);
if(a[n-1]-a[0]>l){
puts("0");
return 0;
}
ll rn;
rn=lower_bound(a,a+n*k,a[0]+1+l)-a;//计算出第一个与第一块木板相差l的木板的编号
ll cnt=rn-n;//计算出能够跳调多少块板
ll ln=0;
ll res=0;
for(int i=0;i<n;i++){
res+=a[ln];
if(cnt>=k-1){//如果能跳过的板子正好可以组成一个木桶,则将左指针右移k-1
cnt-=k-1,ln+=k-1;
}
else if(cnt){//否则直接将左指针移动cnt位,同时清零
ln+=cnt;
cnt=0;
}
ln++;
}
cout<<res<<endl;
return 0;
}