2479 Maximum sum 解题报告

41 篇文章 0 订阅
21 篇文章 0 订阅

 

AccecptTime:  2009-02-03 16:44:05
Language: G++
Memory:  1808K
Time:  547MS
Errors:  3WA
Algorithm: DP

 

 

这道题是昨天写的,刚开始想了半天才想到DP的一个重要思想:选择.选择什么呢?除了中间的分割位还会是什么??嘻嘻:D

但是效率不是很高,有待改进~

ps:这题是2593的兄弟题.不过2593的数据好像太弱了...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
You are given an array a1,a2,…,an, where all elements are different. You have to perform exactly k operations with it. During each operation, you do exactly one of the following two actions (you choose which to do yourself): find two minimum elements in the array, and delete them; find the maximum element in the array, and delete it. You have to calculate the maximum possible sum of elements in the resulting array. Input The first line contains one integer t (1≤t≤104) — the number of test cases. Each test case consists of two lines: the first line contains two integers n and k (3≤n≤2⋅105; 1≤k≤99999; 2k<n) — the number of elements and operations, respectively. the second line contains n integers a1,a2,…,an (1≤ai≤109; all ai are different) — the elements of the array. Additional constraint on the input: the sum of n does not exceed 2⋅105. Output For each test case, print one integer — the maximum possible sum of elements in the resulting array. Example inputCopy 6 5 1 2 5 1 10 6 5 2 2 5 1 10 6 3 1 1 2 3 6 1 15 22 12 10 13 11 6 2 15 22 12 10 13 11 5 1 999999996 999999999 999999997 999999998 999999995 outputCopy 21 11 3 62 46 3999999986 Note In the first testcase, applying the first operation produces the following outcome: two minimums are 1 and 2; removing them leaves the array as [5,10,6], with sum 21; a maximum is 10; removing it leaves the array as [2,5,1,6], with sum 14. 21 is the best answer. In the second testcase, it's optimal to first erase two minimums, then a maximum.
最新发布
05-13
解题思路: 本题是一道贪心题目。我们首先考虑一下,每次操作后,数组的长度都会减少1。因此,我们可以将操作分为两步: - 删除两个最小值 - 删除一个最大值 假设当前数组为 $a$,长度为 $n$,最小值为 $m_1$ 和 $m_2$,最大值为 $M$。则删去 $m_1$ 和 $m_2$ 后,数组变为 $a'$,长度为 $n-2$。删去 $M$ 后,数组变为 $a''$,长度为 $n-1$。 我们考虑一下,如果我们删去 $m_1$ 和 $m_2$ 后,下一步应该删去哪个数,能够使得答案最大。我们发现,如果我们删去 $M$,那么剩下来的数的大小关系不会发生变化。因此,我们可以先删去 $m_1$ 和 $m_2$,然后将剩下的数按照从大到小的顺序排序,再依次删去前 $k-1$ 个数。 如果我们删去 $M$,那么我们需要考虑,下一步应该删去哪两个数,能够使得答案最大。我们发现,如果我们将 $M$ 删掉后,剩下的数可以分为两部分:第一部分是所有小于等于 $m_2$ 的数,第二部分是所有大于 $m_2$ 的数。因此,我们需要在这两个部分中选择两个数来进行删除。我们可以考虑选择第一部分中的最小值 $x$ 和第二部分中的最小值 $y$,使得 $x+y$ 最小。这是因为,如果我们选择了一个较大的数,那么这个数就会对后续的选择产生影响,可能会导致答案不是最优的。 因此,我们可以先将数组排序,然后按照上述策略进行操作,每次操作后更新数组长度和答案即可。 时间复杂度分析:排序的时间复杂度为 $O(n\log n)$,每次操作的时间复杂度为 $O(1)$,总时间复杂度为 $O(tn\log n)$。 参考代码:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值