zoukankan      html  css  js  c++  java
  • [HDOJ4006]The kth great number

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4006

    提供插入查询两个操作,问这些数中第k大的数字是几。

    可以用最小堆完成这个任务,把k看作是堆的容量,堆顶就是第k大的数。这样只需要保留前k大的数输出最小那个就可以了。

     1 #include <algorithm>
     2 #include <iostream>
     3 #include <iomanip>
     4 #include <cstring>
     5 #include <climits>
     6 #include <complex>
     7 #include <fstream>
     8 #include <cassert>
     9 #include <cstdio>
    10 #include <bitset>
    11 #include <vector>
    12 #include <deque>
    13 #include <queue>
    14 #include <stack>
    15 #include <ctime>
    16 #include <set>
    17 #include <map>
    18 #include <cmath>
    19 
    20 using namespace std;
    21 
    22 const int maxn = 100010;
    23 const int INF = 2147483647;
    24 int heap[maxn];
    25 int pos;
    26 
    27 void init() {
    28     pos = 0;
    29     memset(heap, 0, sizeof(heap));
    30     heap[0] = -INF;
    31 }
    32 
    33 void push(int x) {
    34     int i = ++pos;
    35     for(; heap[i>>1] > x; i>>=1) {
    36         heap[i] = heap[i>>1];
    37     }
    38     heap[i] = x;
    39 }
    40 
    41 void pop() {
    42     if(pos == 0) return;
    43     int child = 1;
    44     int i = 1;
    45     int last = heap[pos--];
    46     for(; i<<1 <= pos; i=child) {
    47         child = i<<1;
    48         if(child != pos && heap[child] > heap[child+1]) {
    49             ++child;
    50         }
    51         if(last > heap[child]) {
    52             heap[i] = heap[child];
    53         }
    54         else {
    55             break;
    56         }
    57     }
    58     heap[i] = last;
    59 }
    60 
    61 int n, k, x;
    62 char cmd[2];
    63 
    64 int main() {
    65     // freopen("in", "r", stdin);
    66     while(~scanf("%d %d", &n, &k)) {
    67         init();
    68         while(n--) {
    69             scanf("%s", cmd);
    70             if(cmd[0] == 'I') {
    71                 scanf("%d", &x);
    72                 if(pos < k) push(x);
    73                 else if(heap[1] < x) {
    74                     pop();
    75                     push(x);
    76                 }
    77             }
    78             else {
    79                 printf("%d
    ", heap[1]);
    80             }
    81         }
    82     }
    83     return 0;
    84 }
  • 相关阅读:
    C#简单游戏外挂制作(以Warcraft Ⅲ为例)
    Push模式
    关于VS2005中GridView的自定义分页,单选、多选、排序、自增列的简单应用
    更改SQL表的所有者
    Microsoft Visual Studio 2005中使用水晶报表(非常棒)
    简单介绍一下水晶报表的推与拉两种模式
    SQL函数之四舍五入(转)
    如何制作一个多栏报表
    ASP.NET dropdownlist绑定数据源两种方法
    PUSH模式样板招式
  • 原文地址:https://www.cnblogs.com/kirai/p/4928014.html
Copyright © 2011-2022 走看看