ZOJ3908 贪心

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5635

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
/**
ZOJ3908 贪心
题目大意:给定一个数列,从中挑选出m对来,每对数的和不超过k,所有数对成绩的和最大是多少
解题思路:把所有的数放入multiset中,从大到小找,对于当前数找最大的能满足和不大于k的数,放入数组里存起来,最后去前m大
*/
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
typedef long long LL;
const int maxn=1e5+7;

int n,m,k;
multiset <int> st;
multiset <int>::iterator it1,it2;
vector<int> vec;

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        vec.clear();
        st.clear();
        scanf("%d%d%d",&n,&m,&k);
        for(int i=0;i<n;i++)
        {
            int x;
            scanf("%d",&x);
            if(x<k) st.insert(x);
        }
        while(st.size()>=2)
        {
            it1=st.end();
            it1--;
            it2=st.lower_bound(k-(*it1));
            if(it2==st.end()||it2==it1)it2--;
            int flag=0;
            if(it2==st.begin()&&(*it1)+(*it2)>k)flag=1;
            while((*it1)+(*it2)>k&&(!flag))
            {
                it2--;
                if(it2==st.begin()&&(*it1)+(*it2)>k)flag=1;
            }
            if(it1==it2)it2--;
            if(flag)
            {
                st.erase(it1);
                continue;
            }
            vec.push_back((*it1)*(*it2));
//            printf("%d::%d\n",*it1,*it2);
            st.erase(it1);
            st.erase(it2);
        }
        sort(vec.begin(),vec.end());
        LL ans=0;
        for(int i=vec.size()-1;i>=0&&m;i--)
        {
            m--;
            ans+=vec[i];
        }
        printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(ZOJ3908 贪心)