Codeforces Round #797 (Div. 3) E. Price Maximization
Note that we do not need to consider the numbers x ≥ k x≥k x≥k, we are only interested in the remainder of the division of x x x by k k k, and we simply add the value ⌊ x k \frac{x}{k} kx⌋ to the answer.
We get an array a a a, where a i < k a_i<k ai<k. Let’s sort it and greedily type index pairs i < j i<j i<j such that a i + a j ≥ k ai+aj≥k ai+aj≥k. This can be done with two pointers. Then add the number of matching pairs to the answer counter. This will be the answer to the problem.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int T;cin>>T;
while(T--)
{
int n,k;cin>>n>>k;
multiset<int> b;
long long ans=0;
for(int i=0;i<n;i++)
{
int x;cin>>x;
ans+=x/k;
b.insert(x%k);
}
while(!b.empty())
{
int x=*b.begin();
b.erase(b.begin());
auto it=b.lower_bound(k-x);
if(it!=b.end())
{
b.erase(it);
ans++;
}
}
cout<<ans<<endl;
}
return 0;
}