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
Note
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.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <set>
#include <vector>
#include <stack>
using namespace std;
typedef long long ll;
ll a[1000000];
int main()
{
ll n,k,l;
while(~scanf("%lld%lld%lld",&n,&k,&l))
{
stack<ll> mp1; ///记录比a[1]+l小的数
queue<ll> mp2; ///记录比a[1]+l大的数
for(int i=1; i<=n*k; i++)
scanf("%lld",&a[i]);
sort(a+1,a+1+n*k);
ll maxn=a[1]+l;
for(int i=1; i<=n*k; i++)
{
if(a[i]>maxn)
mp2.push(a[i]);
else
mp1.push(a[i]);
}
ll ans=0;
int cnt=0;
if(mp1.size()<n) ///满足题意的数字不足够拼成n个水桶
{
printf("0\n");
continue;
}
else
{
while(!mp1.empty())
{
ll res=mp1.top();
ans+=mp1.top();
mp1.pop();
int i,flog=0;
for(i=1;i<k;i++)
{
if(!mp2.empty())
mp2.pop();
else
{
flog=1;
break;
}
}
if(flog)
{
for(;i<k;i++)
{
if(i==k-1)
ans+=mp1.top();
mp1.pop();
}
ans-=res; ///初始时加上了但该木桶的容量不是res,所以要减去
break;
}
}
while(!mp1.empty())
{
for(int j=1;j<=k;j++)
{
if(j==k)
ans+=mp1.top();
mp1.pop();
}
}
printf("%lld\n",ans);
}
while(!mp1.empty())
mp1.pop();
while(!mp2.empty())
mp2.pop();
}
return 0;
}
/*
4 2 1
2 2 1 2 3 2 2 3
2 1 0
10 10
1 2 1
5 2
3 2 1
1 2 3 4 5 6
*/