Average and Median(500)dp,二分 AtCoder Beginner Contest 236
E - Average and Median /
Time Limit: 2 sec / Memory Limit: 1024 MB
Score : 500 points
Problem Statement
We have N cards. The i-th card (1≤i≤N) has an integer A
i
?
written on it.
Takahashi will choose any number of cards from these. However, for each i (1≤i≤N?1), at least one of the i-th and (i+1)-th cards must be chosen.
Find the following values.
The maximum possible average of the integers written on the chosen cards
The maximum possible median of the integers written on the chosen cards
Here, the median of the n integers is defined to be the ?
2
n
?
?-th smallest of them, where ?x? is the smallest integer not less than x.
Constraints
2≤N≤10
5
1≤A
i
?
≤10
9
All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A
1
?
… A
N
?
Output
Print two lines. The first and second lines should contain the maximum possible average and maximum possible median of the integers written on the chosen cards, respectively. For the average, your output will be considered correct when its relative or absolute error from the exact answer is at most 10
?3
.
Sample Input 1
Copy
6
2 1 2 1 1 10
Sample Output 1
Copy
4
2
Choosing the 2-nd, 4-th, and 6-th cards makes the average of the written integers
3
12
?
=4, which is the maximum possible.
Choosing the 1-st, 3-rd, 5-th, and 6-th cards makes the median of the written integers 2, which is the maximum possible.
Sample Input 2
Copy
7
3 1 4 1 5 9 2
Sample Output 2
Copy
5.250000000
4
For the average, your output may contain some degree of error: for example, the output 5.2491 is still considered correct. For the median, however, the exact value must be printed.
題意 :
- 有n個數,從其中選若干個,規則是?i(1≤i≤n?1)\forall i(1 \leq i \leq n-1)?i(1≤i≤n?1),都滿足i和i+1個中 至少 被選擇一個;求所有滿足的方案中,選出的數的,最大平均值 和 最大中位數(第n/2n/2n/2向上取整個小的)
思路 :
- 最大化平均值或者中位數 最常見的方法是 “結果是否超過k”,然后通過二分查找找出答案
- “平均值超過k嗎”:數列的平均值超過k,等價于 數列中每個數都減去k后,新的數列的元素和大于0,因此,定義一個新的數組bi=ai?kb_i = a_i - kbi?=ai??k,然后判斷是否b_i的最大和大于0
- 首先我們看看這里中位數的定義,相當于如果4個數,第二個數是中位數;如果5個數,第三個數是中位數
- “中位數超過k嗎”:數列的中位數超過k,等價于 超過k的元素的個數 小于等于k;因此,定義bi=1/?1b_i=1/-1bi?=1/?1,當a_i >= k時,b_i為1,然后判斷是否b_i的最大和是正數
- 那么如果找出b_i的最大和呢?答案是通過dp;fif_ifi?表示,考慮前i個元素時,第i個元素被選擇的情況下,b數組的最大和;gig_igi?表示,考慮前i個元素時,第i個元素不被選擇的情況下,b數組的最大和;甚至可以不使用dp的方法,枚舉到第i個元素時,考慮第i-1個元素,選擇第i-1個元素的結果為sel,不選擇的結果為unsel,則選擇第i個元素的結果為max(sel, unsel) + x,不選擇的結果為unsel,選擇為max(sel, unsel) + x,最后返回max(sel, unsel)
總結
以上是生活随笔為你收集整理的Average and Median(500)dp,二分 AtCoder Beginner Contest 236的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 90%的程序员都写错的算法-二分查找万能
- 下一篇: 黑马程序员pink老师前端入门教程,零基