zoukankan      html  css  js  c++  java
  • [Luogu]中位数

    Description

    Luogu1168

    Solution

    一种神奇的做法:开一个大根堆和小根堆,保证大根堆比小根堆多1个元素,且大根堆堆顶元素比小根堆堆顶元素小,那么大根堆堆顶就是中位数。插入的时候用交换堆顶元素的方法维护一下这个性质就行。

    Code

    #include <cstdio>
    #include <queue>
    
    const int N = 100010;
    
    int n, a[N];
    std::priority_queue<int> big;
    std::priority_queue<int, std::vector<int>, std::greater<int> > small;
    
    int main() {
    	scanf("%d", &n);
    	for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
    	int p = 1;
    	big.push(a[p++]);
    	printf("%d
    ", big.top());
    	if (!n%2) n--;
    	while (p < n) {
    		int x = a[p++], y = a[p++];
    		if (x > y) std::swap(x, y);
    		big.push(x);
    		small.push(y);
    		if (big.top() > small.top()) {
    			int x = big.top(), y = small.top();
    			big.pop(); big.push(y);
    			small.pop(); small.push(x);
    		}
    		printf("%d
    ", big.top());
     	}
    	return 0;
    }
    
  • 相关阅读:
    单词 统计
    第九周周进度报告
    日常总结
    Docker 初识
    读书笔记
    《未来简史》有感
    自己的Java规范文档
    nginx自动部署脚本
    jdk 自动化脚本
    我Java学习时的模样(三)
  • 原文地址:https://www.cnblogs.com/wyxwyx/p/lg1168.html
Copyright © 2011-2022 走看看