hdu 4006 The kth great number(STL 之set/priority_queue)
用stl 写代码明显是短了,时间也直线上升
不用stl 写的
#include<stdio.h> #include<stdlib.h> int f[10000002]; int cmp ( const void *a , const void *b ) { return *(int *)a - *(int *)b; } int main() { int a,i,k,n,s,e; char st[3]; while(scanf("%d %d",&n,&k)!=EOF) { for(i=0;i< k;i++) { scanf("%s %d",st,&f[i]); } qsort(f,k,sizeof(f[0]),cmp); e=k-1; s=0; n=n-k; while(n--) { scanf("%s",st); if(st[0]=='Q') printf("%d\n",f[s]); else { scanf("%d",&a); if(a<=f[s])continue; if(a>f[(s+e)/2]) { for(i=e+1;f[i-1]>a;i--) f[i]=f[i-1]; f[i]=a; e++; s++; } else { for(i=s;f[i+1]<a;i++) f[i]=f[i+1]; f[i]=a; } } } } return 0; }
朴素写法: 时间 125 ms
最小优先队列:578 ms
#include <iostream> #include <set> #include <queue> using namespace std; int main() { int n,k; while(cin>>n>>k) { priority_queue <int,vector<int>,greater<int> > p; while(n--) { char str;cin>>str; if(p.size()>k) p.pop(); if(str=='I') { int m;cin>>m; p.push(m); } else cout<<p.top()<<endl; } } return 0; }
set 点集 625 ms
#include <iostream> #include <set> using namespace std; int main() { int n,k; while(cin>>n>>k) { multiset<int> p; while(n--) { char str;cin>>str; if(p.size()>k) p.erase(p.begin()); if(str=='I') { int m;cin>>m; p.insert(m); } else cout<<*p.begin()<<endl; } } return 0; }
Just a little, maybe change the world