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,L;
表示你需要拼出 n个桶,每个桶由k个板子组成,每个桶的容量之间的差值不能大于L (木桶效应应该都知道吧,容量取决于最短的那一块木板)
输入k*n 块木板,求出最大的容量。
思路:
关键就在于短板效应,比如 四块板子,组成两个桶 1,2,3,4 ,他的组合方式 肯定是 [1,2],[3,4] ,也就是说 每个桶的最小的木板要尽量大。
还有各个桶的最小的木板之间的差值不能 大于 L 。我们先不要考虑组成的容量最大的问题,在n*k块木板里面,先进性从小到大排序,分为两部分,第一部分是[ a[0] , a[0] + L ] ,第二部分是 [ a[0]+ L +1 , a[ n*k-1 ] ]
因为差值不能大于L,所以第二部分的值绝对不能成为最短的板,因为假如成为了最短的板,就肯定不满足条件了。 所以第二部分的值应该和第一部分组合,而且我们要贪心 就是 取第一部分一块木板,取(k-1)块第二部分的板。而且第一部分的板要从大到小取,假如第一部分都取完了,第二部还有剩余,说明不符合条件,只能输出 0 了。
假如第二部分取完了,第一部分还有的话,就根据我们上面1,2,3,4的例子取就好了。
还有注意一下当k=1的时候的情况。代码里可以体现。
#include<bits/stdc++.h> using namespace std; long long a[100005]; int main() { int n,k,l; cin >> n >> k >> l; for(int i=0;i<n*k;i++) cin >> a[i]; sort(a,a+n*k); if(k==1) { if(a[n*k-1] - a[0] <= l) { long long sum=0; for(int i=0;i<n*k;i++) sum+=a[i]; cout << sum << endl; } else cout << 0 << endl; return 0; } int pos = lower_bound(a,a+n*k,a[0]+l+1) - a; //找到两个部分的临界点 int index=pos; int num = (n*k - pos) / (k-1); //这个 num 代表 第二部分 最多可以组成多少组 if(num > pos) cout << 0 << endl; //说明 第二部分有剩余,第一部分都被用完了 else { long long sum=0; for(int i=pos-1;i>=pos-num;i--) sum+=a[i]; for(int i=0;i<pos-num;i+=k) sum+=a[i]; cout << sum << endl; } }