The bored Bob is playing a number game. In the beginning, there aren numbers. For each turn, Bob will take out two numbers from the remaining numbers, and get the product of them. There is a condition that the sum of two numbers must be not larger thank.
Now, Bob is curious to know what the maximum sum of products he can get, if he playsat most m turns. Can you tell him?
The first line of input contains a positive integerT, the number of test cases.For each test case, the first line is three integersn, m(0≤ n, m ≤100000) and k(0≤k ≤20000). In the second line, there are n numbers ai(0≤ai ≤10000, 1≤ i ≤n).
For each test case, output the maximum sum of products Bob can get.
2
4 2 7
1 3 2 4
3 2 3
2 3 1
14
2
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5635
题目大意:n个数字,最多m次操作,每次选两个数字出来得到它们的乘积,选的时候要求两个数字的和不能大于k,求最后所能得到的最大值
题目分析:从小到大排序,从大数字开始找,找与其配对的最优解,这里最优的含义是与其相加小于等于k的最大值,因为最优的情况显然是两个数字差值最小且加起来越接近k,找的时候二分,找到以后把这两个数字删去,重复操作,直到数字个数小于2,然后在记录的最优值中选最大的m个相加,因为数字可能重复,用multiset维护,注意开始数字大于k的话直接不用insert,还有删数字的时候有几个re点注意下
#include <cstdio> #include <cstring> #include <algorithm> #include <set> #define ll long long using namespace std; int const MAX = 1e5 + 5; multiset <ll> mst; multiset <ll> :: iterator it1, it2; ll ans[MAX]; bool cmp(ll a, ll b) { return a > b; } int main() { int T; scanf("%d", &T); while(T --) { mst.clear(); int n, m, k, cnt = 0; ll tmp; scanf("%d %d %d", &n, &m, &k); for(int i = 0; i < n; i++) { scanf("%lld", &tmp); if(tmp <= k) mst.insert(tmp); } while(true) { int sz = mst.size(); if(sz < 2) break; //printf("sz = %d\n", (int) mst.size()); it1 = mst.end(); it1 --; ll fir = *it1; mst.erase(it1); it2 = mst.lower_bound(min(fir, k - fir)); if(it2 == mst.end()) it2--; if(it2 == mst.begin() && *it2 > (k - fir)) continue; if(*it2 <= k - fir) { ans[cnt++] = fir * ( *it2); mst.erase(it2); } else { it2 --; ans[cnt++] = fir * (*it2); mst.erase(it2); } } sort(ans, ans + cnt, cmp); ll res = 0; for(int i = 0; i < min(m, cnt); i++) res += ans[i]; printf("%lld\n", res); } }