hdu 4006 求第k大的数

View Code
#include<queue>
#include<iostream>
#include<vector>
using namespace std;
struct mycmp
{
bool operator()(const int &a,const int &b)
{
return a>b;
}
};//这里表示从小到大排列,最小的数在队头,随时准备走出队列
int main()
{
int n,k,val;
char str[5];
int count;
while(scanf("%d%d",&n,&k)!=EOF)
{
priority_queue<int,vector<int>,mycmp> pq;
while(n--)
{
scanf("%s",str);
if(str[0]=='I')
{
scanf("%d",&val);
pq.push(val);
while(pq.size()>k)
pq.pop();
}
else
{
printf("%d\n",pq.top());
}
}
}
return 0;
}


set 做法,set内部结构是红黑树,听说效率蛮高,尝试着写了一下,A西~

View Code
#pragma warning (disable : 4786)
#include<stdio.h>
#include<string.h>
#include<set>
#include<iostream>
using namespace std;
int main()
{
char str[5];
int val,n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
multiset<int> s;
while(n--)
{
scanf("%s",str);
if(str[0]=='I')
{
scanf("%d",&val);
s.insert(val);
multiset<int>::iterator it;
while(s.size()>k)
{
it=s.begin();
s.erase(it);//原来的错误:s.erase(*it);删除应该是删除某个位置的指针,如果删除元素的话,所有的相同元素都会被删除
}
}
else
{
multiset<int>::iterator it;
it=s.begin();
printf("%d\n",*it);
}
}
}
return 0;
}

posted @ 2011-09-23 15:25  Because Of You  Views(850)  Comments(1Edit  收藏  举报