开始直接暴力,然后果断挂掉。T_T...后来看到DIcuss里有人说用Binary heap。然后就在想怎么用堆优化,想了半天没想到。然后看大牛的思路。鹈鹄灌顶啊!!!
思路:先存数列长度的一半+1,然后建立小顶堆。然后输入剩下的元素,如果输入的元素大于堆顶元素,则把堆顶替换掉。再调整一次堆。
My Code:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 125005;
int heap[N];
void heap_adjust(int p, int len) {
int i, j, tmp;
i = p; j = i << 1;
tmp = heap[p];
while(j <= len) {
if(j < len && heap[j] > heap[j+1]) j++;
if(tmp > heap[j]) {
heap[i] = heap[j];
i = j; j = i << 1;
}
else break;
}
heap[i] = tmp;
}
int main() {
//freopen("data.in", "r", stdin);
int h, n, i, t;
while(~scanf("%d", &n)){
h = n/2 + 1;
for(i = 1; i <= h; i++)
scanf("%d", &heap[i]);
for(i = h/2; i > 0; i--)
heap_adjust(i, h);
if(n == 2) {
printf("%.1lf\n", (heap[1]*1.0 + heap[2]*1.0)/2);
return 0;
}
for(i = h+1; i <= n; i++) {
scanf("%d", &t);
if(t > heap[1]) {
heap[1] = t;
heap_adjust(1, h);
}
}
if(n&1) printf("%.1lf\n", heap[1]*1.0);
else {
heap[2] = heap[2] > heap[3] ? heap[3] : heap[2];
printf("%.1lf\n", (heap[1]*1.0 + heap[2]*1.0)/2);
}
}
return 0;
}