ZOJ3908 贪心

26 篇文章 1 订阅

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 nm(0≤ nm ≤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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值