中位数优先容器

要求编写一个容器,它可支持两种操作:push()和pop(),push(K)操作可将元素K放入容器,pop()操作可将容器中的中位值弹出。

例如:push(1),push(2),push(3)后pop()[输出为2]。

解决方法,创建一个最大值优先的优先队列,将其记为左队列ql,创建一个最小值优先的优先队列,将其记为右队列qr,

我们规定ql不为空时,ql.top()为中位值,记为mid,对于push(k),如果k>mid,则将k压入右边优先队列qr,如果k<=mid怎将其压入

左边优先队列ql,然后将左右两个队列做平衡处理。pop()则只需将ql.top()的值弹出后做平衡处理即可。这种方法和快排算法中将

一个序列分成大于mid的和小于等于mid的两部分的做法相似。

题目链接:http://acm.hdu.edu.cn/diy/contest_showproblem.php?cid=16719&pid=1005

代码:

  1. #include<cstdio>  
  2. #include<vector>  
  3. #include<queue>  
  4.   
  5. using namespace std;  
  6.   
  7. struct cmp1    
  8. {      
  9.     bool operator ()(int &a,int &b)    
  10.     {      
  11.         return a>b;//最小值优先       
  12.     }      
  13. };      
  14.   
  15. struct cmp2    
  16. {      
  17.     bool operator ()(int &a,int &b)    
  18.     {      
  19.         return a<b;//最大值优先       
  20.     }      
  21. };   
  22.   
  23. priority_queue<int,vector<int>,cmp1>qr;//最小值优先       
  24. priority_queue<int,vector<int>,cmp2>ql;//最大值优先  
  25. int ls,rs;  
  26.   
  27. void balance(void)  
  28. {  
  29.      int idx=(ls+rs+1)/2;  
  30.      while(ls<idx)  
  31.      {  
  32.           int k=qr.top();  
  33.           ql.push(k);  
  34.           qr.pop();  
  35.           ls++;  
  36.           rs--;  
  37.      }  
  38.      while(ls>idx)  
  39.      {  
  40.           int k=ql.top();  
  41.           qr.push(k);  
  42.           ql.pop();  
  43.           ls--;  
  44.           rs++;  
  45.      }  
  46.        
  47. }  
  48.   
  49. void push(int k)  
  50. {  
  51.      if(ls==0) {  
  52.           ql.push(k);  
  53.           ls++;  
  54.           return ;  
  55.      }  
  56.      int mid=ql.top();  
  57.      if(k>mid) qr.push(k),rs++;  
  58.      else ql.push(k),ls++;  
  59.      balance();  
  60. }  
  61.   
  62. void pop(void)  
  63. {  
  64.      if(ls<=0) {  
  65.           printf("No Element!\n");  
  66.           return ;  
  67.      }  
  68.      int ans=ql.top();  
  69.      ql.pop();  
  70.      ls--;  
  71.      balance();  
  72.      printf("%d\n",ans);  
  73. }  
  74.   
  75. int main()  
  76. {  
  77.     int n;  
  78.     while(scanf("%d", &n)!=EOF){  
  79.           ls=rs=0;  
  80.           qr=priority_queue<int,vector<int>,cmp1>();  
  81.           ql=priority_queue<int,vector<int>,cmp2>();  
  82.           for(int i=0;i<n;i++) {  
  83.                 int c,k;  
  84.                 scanf("%d",&c);  
  85.                 if(c==0) {  
  86.                      scanf("%d",&k);  
  87.                      //printf("push %d\n",k);  
  88.                      push(k);  
  89.                 }  
  90.                 else pop();  
  91.                 //printf("ls=%d rs=%d\n",ls,rs);  
  92.           }  
  93.           printf("\n");  
  94.     }  
  95.     return 0;  
  96. }  
原文地址:https://www.cnblogs.com/mfryf/p/2716568.html