hihoCoder#1105 题外话·堆

原题地址

 

有没有更优雅地堆模板啊,总感觉我写的有些啰嗦

 

代码:

 1 #include <iostream>

 2 

 3 using namespace std;

 4 

 5 #define MAX_NODE 100008

 6 

 7 struct Heap {

 8   int core[MAX_NODE];

 9   int size;

10 

11   Heap() : size(0) {}

12 

13   void push(int w) {

14     int c, p;

15     core[++size] = w;

16     c = size;

17     p = c >> 1;

18     while (c > 1 && core[p] < core[c]) {

19       swap(core[p], core[c]);

20       c = p;

21       p >>= 1;

22     }

23   }

24 

25   int pop() {

26     int res = core[1];

27     int c, k;

28     swap(core[1], core[size]);

29     size--;

30     c = 1;

31     k = c << 1;

32     while (k <= size) {

33       if (k + 1 <= size && core[k + 1] > core[k])

34         k = k + 1;

35       if (core[k] <= core[c])

36         break;

37       swap(core[k], core[c]);

38       c = k;

39       k <<= 1;

40     }

41     return res;

42   }

43 };

44 

45 int main() {

46   int N, w;

47   char t;

48   Heap h;

49 

50   scanf("%d\n", &N);

51   while (N--) {

52     scanf("%c", &t);

53     if (t == 'A') {

54       scanf("%d\n", &w);

55       h.push(w);

56     }

57     else {

58       scanf("%c", &t);

59       printf("%d\n", h.pop());

60     }

61   }

62   return 0;

63 }

 

你可能感兴趣的:(code)