【每日一题】4月9日题目精讲 Running Median
文章目錄
- 題目:
- 題意:
- 題解一:
- 題解二:
題目:
–>鏈接<—
時間限制:C/C++ 5秒,其他語言10秒 空間限制:C/C++ 65536K,其他語言131072K 64bit
IO Format:%lld
題目描述
For this problem, you will write a program that reads in a sequence of
32-bit signed integers. After each odd-indexed value is read, output
the median (middle value) of the elements received so far.
輸入描述:
The first line of input contains a single integerP(1≤P≤1000), which is the number of data sets that follow. The
first line of each data set contains the data set number, followed by
a space, followed by an odd decimal integer (1≤M≤9999), giving the total number of signed integers to be
processed. The remaining line(s) in the dataset consists of the
values, 10 per line, separated by a single space. The last line in the
dataset may contain less than 10 values.
輸出描述:
For each data set the first line of output contains the data set
number, a single space and the number of medians output (which should
be one-half the number of input values plus one). The output medians
will be on the following lines, 10 per line separated by a single
space. The last line may have less than 10 elements, but at least 1
element. There should be no blank lines in the output.
示例1
輸入
3
1 9
1 2 3 4 5 6 7 8 9
2 9
9 8 7 6 5 4 3 2 1
3 23
23 41 13 22 -3 24 -31 -11 -8 -7
3 5 103 211 -311 -45 -67 -73 -81 -99
-33 24 56
輸出
1 5
1 2 3 4 5
2 5
9 8 7 6 5
3 12
23 23 22 22 13 3 5 5 3 -3
-7 -3
題意:
給你m個數,一次輸入,每當輸入的個數為奇數時,輸出按大小排列最中間的數
比如1 5 6 7 8
一開始輸入1,輸出1
然后輸入1 5,不輸出
輸入1 5 6,輸出5
輸入1 5 6 7,不輸出
輸入1 5 6 7 8,輸出6
題解一:
可以用堆來做
w1為大堆,w1用于存放小值
w2為小堆,w2存放大值
比如上面那個例子1 5 6 7 8
奇數位存在w1,偶數存在w2
如果w1.top()>w2.top(),就是w1的最大比w2的最小值大,就將這兩個值互換,始終保證,w1的值比w2的任意一個都小,這樣無論數據怎么讀入,w1的最大值始終都是最中間的數
看下面模擬:
第一輪:
w1:1
w2:0
二:
w1:1
w2:5
三:
w1:1 6
w2:5
6>5
w1:1 5
w2:6
四
w1:1 5
w2: 7 6
五
w1:1 5 8
w2: 7 6
8>6
w1:1 5 6
w2; 7 8
這樣每奇數輪,w1的top位就是答案
(這個題的格式我一開始一直沒注意。。。)
題解二:
我看很多人都是這么做的,但是只能過50%的數據。。包括我自己
我看了清楚姐姐的代碼稍微改一下:
我們在讀入一個數后,直接與w1.top比較,小于就存進去,大了就存w2里
當w1的數量多了,就把堆頂拿出給w2(小根堆)
w2多了就給大根堆
這樣維護出來其實和上面的方法差不多
因為總數是奇數,兩個堆數量一定不一樣,多的那方,堆頂就是答案
代碼:
清楚阿姨(狗頭 )代碼:
總結
以上是生活随笔為你收集整理的【每日一题】4月9日题目精讲 Running Median的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: D3学习之地图
- 下一篇: 字符,字符集,字符编码