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個(gè)數(shù),從其中選若干個(gè),規(guī)則是?i(1≤i≤n?1)\forall i(1 \leq i \leq n-1)?i(1≤i≤n?1),都滿足i和i+1個(gè)中 至少 被選擇一個(gè);求所有滿足的方案中,選出的數(shù)的,最大平均值 和 最大中位數(shù)(第n/2n/2n/2向上取整個(gè)小的)
思路 :
- 最大化平均值或者中位數(shù) 最常見的方法是 “結(jié)果是否超過k”,然后通過二分查找找出答案
- “平均值超過k嗎”:數(shù)列的平均值超過k,等價(jià)于 數(shù)列中每個(gè)數(shù)都減去k后,新的數(shù)列的元素和大于0,因此,定義一個(gè)新的數(shù)組bi=ai?kb_i = a_i - kbi?=ai??k,然后判斷是否b_i的最大和大于0
- 首先我們看看這里中位數(shù)的定義,相當(dāng)于如果4個(gè)數(shù),第二個(gè)數(shù)是中位數(shù);如果5個(gè)數(shù),第三個(gè)數(shù)是中位數(shù)
- “中位數(shù)超過k嗎”:數(shù)列的中位數(shù)超過k,等價(jià)于 超過k的元素的個(gè)數(shù) 小于等于k;因此,定義bi=1/?1b_i=1/-1bi?=1/?1,當(dāng)a_i >= k時(shí),b_i為1,然后判斷是否b_i的最大和是正數(shù)
- 那么如果找出b_i的最大和呢?答案是通過dp;fif_ifi?表示,考慮前i個(gè)元素時(shí),第i個(gè)元素被選擇的情況下,b數(shù)組的最大和;gig_igi?表示,考慮前i個(gè)元素時(shí),第i個(gè)元素不被選擇的情況下,b數(shù)組的最大和;甚至可以不使用dp的方法,枚舉到第i個(gè)元素時(shí),考慮第i-1個(gè)元素,選擇第i-1個(gè)元素的結(jié)果為sel,不選擇的結(jié)果為unsel,則選擇第i個(gè)元素的結(jié)果為max(sel, unsel) + x,不選擇的結(jié)果為unsel,選擇為max(sel, unsel) + x,最后返回max(sel, unsel)
總結(jié)
以上是生活随笔為你收集整理的Average and Median(500)dp,二分 AtCoder Beginner Contest 236的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 90%的程序员都写错的算法-二分查找万能
- 下一篇: Maven自动化构建工具