POJ 3784 Running Median(動態維護中位數)
阿新 • • 發佈:2018-10-14
常數 nes 意思 elements sample owin roc 進行 there
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.
Description
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.Input
The first line of input contains a single integer P, (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 M, (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.Output
Sample Input
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
Sample Output
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
題目意思:對於n個數,每輸入到奇數個數,便求一次中位數。
解題思路:我開始就直接暴力,到了奇數位,sort一下,找出中位數,這樣在UVAlive上沒有超時,但在poj上是超時的,看了看網上的代碼才知道處理這樣一個動態的中位數使用堆來維護,而這個堆使用優先隊列來模擬,一周內第二次見到優先隊列了。維護一個大根堆和一個小根堆,且保證大根堆裏的所有數都比小根堆裏的所有數小,而且大根堆的大小等於小根堆或者大1,則大根堆堆頂就是中位數。對於新插入的數,與中位數比較決定插入哪個堆中,插入之後維護一下兩個堆的大小。每次維護需要進行常數個堆上的操作,所以復雜度O(nlogn)。
1 #include<cstdio> 2 #include<cstring> 3 #include<queue> 4 using namespace std; 5 priority_queue<int,vector<int>,greater<int> > bh;///從小到大 6 priority_queue<int,vector<int>,less<int> > sh;///從大到小 7 int main() 8 { 9 int t,n,num; 10 int i,j,m,p,q,x,y,z,K; 11 scanf("%d",&t); 12 while (t--) 13 { 14 scanf("%d%d",&num,&n); 15 printf("%d %d\n",num,n/2+1); 16 while (!bh.empty()) 17 { 18 bh.pop(); 19 } 20 while (!sh.empty()) 21 { 22 sh.pop(); 23 } 24 for (i=1; i<=n; i++) 25 { 26 scanf("%d",&x); 27 if (sh.empty()||sh.top()>x) 28 { 29 sh.push(x);///放入小堆 30 } 31 else 32 { 33 bh.push(x);///放入大堆 34 } 35 if (sh.size()>(i+1)/2) 36 { 37 x=sh.top(); 38 sh.pop(); 39 bh.push(x); 40 } 41 if (sh.size()<(i+1)/2) 42 { 43 x=bh.top(); 44 bh.pop(); 45 sh.push(x); 46 } 47 if (i%2) 48 { 49 printf("%d",sh.top()); 50 if (i==n||(i+1)%20==0) 51 { 52 printf("\n"); 53 } 54 else 55 { 56 printf(" "); 57 } 58 } 59 } 60 } 61 return 0; 62 }
POJ 3784 Running Median(動態維護中位數)