题目链接:http://poj.org/problem?id=1442
堆的练手题。搞一个大根堆和一个小根堆,其余YY一下就好
1 #include<cstdio> 2 #include<cstdlib> 3 #include<cstring> 4 #include<algorithm> 5 using namespace std; 6 #define lowbit(a) ((a)&(-a)) 7 #define max(a, b) ((a)>(b)?(a):(b)) 8 #define min(a, b) ((a)<(b)?(a):(b)) 9 #define MAXN 30010 10 #define PI 3.1415926 11 #define E 2.718281828 12 #define INF 0x777777f 13 typedef long long LL; 14 15 struct heap{ 16 #define hMAXN 30010 17 int hCnt, a[hMAXN]; 18 inline void clear(){hCnt = 0;} 19 inline void swp(int p, int q){a[q] = a[p];} 20 void swim(int p){ 21 int tmp[] = {a[p]}; 22 for (int q = p >> 1; q > 0; p = q, q >>= 1){ 23 if (a[q] > tmp[0]){ 24 swp(q, p); 25 } else break; 26 } a[p] = tmp[0]; 27 } 28 void sink(int p){ 29 int tmp[] = {a[p]}; 30 for (int q = p << 1; q <= hCnt; p = q, q <<= 1){ 31 if (a[q] > a[q+1] && q < hCnt) q++; 32 if (a[q] < tmp[0]){ 33 swp(q, p); 34 } else break; 35 } a[p] = tmp[0]; 36 } 37 void push(int x){a[++hCnt] = x; swim(hCnt);} 38 int pop(int p){int ret = a[p]; swp(hCnt, p); a[hCnt] = 0; hCnt--; swim(p); sink(p); return ret;} 39 } h1, h2; 40 int n, m, a[MAXN], b[MAXN]; 41 42 int main(){ 43 scanf("%d%d", &n, &m); 44 for (int i = 1; i <= n; i++) 45 scanf("%d", &a[i]); 46 for (int i = 1; i <= m; i++) 47 scanf("%d", &b[i]); 48 int t = 1; 49 for (int i = 1; i <= n; i++){ 50 if (a[i] < -h1.a[1] && h1.hCnt){ 51 int tmp = h1.pop(1); 52 h1.push(-a[i]); 53 h2.push(-tmp); 54 } 55 else { 56 h2.push(a[i]); 57 } 58 for ( ; i == b[t]; t++){ 59 printf("%d\n", h2.a[1]); 60 h1.push(-h2.pop(1)); 61 } 62 } 63 return 0; 64 }
时间: 2024-10-06 03:52:29