Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

贴码加注释留念,堆太强大了,stl太强大了,数据结构太强大了。。。

Posted by yuanchuanshun at 2011-01-25 12:31:35 on Problem 1442
/*1442 Accepted 632K 157MS C++ 1378B 2011-01-25 12:27:10*/
#include<iostream>
#include<algorithm>
#include<queue>
#include<stdio.h>
using namespace std;
struct MAXHEAP{ 
    int x;
    bool operator<(MAXHEAP a)const{
        return x<a.x;
    }
}h;
//最大堆,顶端元素最大,如果存放整个数列里的前k小的元素,那么自然就是整个数列第k小元素;
struct MINHEAP{
    int x;
    bool operator<(MINHEAP a)const{
        return x>a.x;
    }
}g;
//最小堆,存放其余元素;
priority_queue<MAXHEAP>maxheap;
priority_queue<MINHEAP>minheap;
int a[30010];
int main()
{
    int n,m,i,k,x;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        for(i=1;i<=n;i++)scanf("%d",a+i);
        int pos=0;
        for(k=1;k<=m;k++){
            scanf("%d",&x);
            while(pos<x){  
                g.x=a[++pos];           
                minheap.push(g); //将新进入的数加入到最小堆中; 
            }
            while(maxheap.size()<k){ //将最大堆中的元素个数补充到k个; 
                h.x=minheap.top().x;
                maxheap.push(h);
                minheap.pop();
            }
            while(!minheap.empty()&&maxheap.top().x>minheap.top().x){
            //交换顶端元素,保证maxheap的top元素比minheap的top元素小;
               //如果优先队列为空,调用top()会出现RE!!!               
                int t1=maxheap.top().x,t2=minheap.top().x;
                maxheap.pop(), minheap.pop();
                h.x=t2, g.x=t1;
                maxheap.push(h), minheap.push(g);
            }    
            printf("%d\n",maxheap.top().x);
        }
    }
}         

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator