ZOJ-3908-Number Game

来源:互联网 发布:c语言闰年月份计算 编辑:程序博客网 时间:2024/05/21 11:02

ZOJ-3908-Number Game


                    Time Limit: 2 Seconds      Memory Limit: 65536 KB

The bored Bob is playing a number game. In the beginning, there are n 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 than k.

Now, Bob is curious to know what the maximum sum of products he can get, if he plays at most m turns. Can you tell him?

Input

The first line of input contains a positive integer T, the number of test cases. For each test case, the first line is three integers n, 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).

Output

For each test case, output the maximum sum of products Bob can get.

Sample Input
2
4 2 7
1 3 2 4
3 2 3
2 3 1

Sample Output
14
2

题目链接:ZOJ-3908

题目大意:n个数字,最多m次操作,每次选两个数字出来得到它们的乘积,选的时候要求两个数字的和不能大于k,求最后所能得到的最大值

以下是代码:

#include <vector>#include <map>#include <set>#include <algorithm>#include <iostream>#include <cstdio>#include <cmath>#include <cstdlib>#include <string>#include <cstring>using namespace std;vector <int> a;int ans[100010] = {0};int main(){    int t;    cin >> t;    while(t--)    {        int n,m,k;        cin >> n >> m >> k;        a.clear();        for (int i = 0; i < n; i++)        {            int num;            cin >> num;            a.push_back(num);        }        sort(a.begin(),a.end());        int i;        for (i = n - 1; i >= 0; i--)        {            if (a[i] + a[0] <= k)                break;          }        a.erase(a.begin() + i + 1,a.end());        int p = 0;        memset(ans,0,sizeof(ans));          while(a.size() > 1)        {            int len = a.size() - 1;            a.erase(--a.end());            int num = upper_bound(a.begin(),a.end(),k - a[len]) - a.begin();            if (num == 0) continue;            ans[p++] = a[num - 1] * a[len];            a.erase(a.begin() + num - 1);        }        sort(ans,ans + p);        long long last = 0;        for (int i = p - 1; i >= 0 && m; i--,m--)        {            last += ans[i];        }        cout << last << endl;    }    return 0;}
0 0