Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 8253 Accepted Submission(s): 3265
8 3 I 1 I 2 I 3 Q I 5 Q I 4 Q
1 2 3HintXiao Ming won't ask Xiao Bao the kth great number when the number of the written number is smaller than k. (1=<k<=n<=1000000).
超时,跪了!!若用循环法超找到第k大的值,然后再将前面的值再存进去会超时,k值很大,k<=1000000。
解决超时,将队列按小到大的顺序排列,当队列的长度大于k时,则删除对顶元素。这样就使得对顶元素永远是第k大的数。
具体代码如下:
#include<cstdio> #include<cstring> #include<queue> using namespace std; int main() { int n,k,a; char str[3]; while(scanf("%d%d",&n,&k)!=EOF) { priority_queue<int,vector<int>,greater<int> >q;//注意更新队列 while(n--) { scanf("%s",str); if(strcmp(str,"I")==0) { scanf("%d",&a); q.push(a); if(q.size()>k) q.pop(); } else printf("%d\n",q.top()); } } return 0; }