vector如何实现有序数组?

有序数组维护一个序列 a 1 , a 2 , . . . , a n a_1,a_2,...,a_n a1,a2,...,an,使得其保持有序,而且支持插入时间为 O ( l o g n ) O(logn) O(logn)的操作。python中有第三方库SortedList,C++并没有这样的stl库。

但我们可以使用vector和lower_bound进行类似的操作:使用lower_bound找到插入的位置,使用vector::insert插入该位置。

如题 洛谷P1168 中位数

正统的做法是维护一个最大堆和一个最小堆,最小堆的数在后半部分(比最大堆大),最大堆的数在前半部分,每次取最大堆的堆顶。但是写起来比较麻烦。

用有序数组可以这么写:

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
#include <cstring>
#include <climits>
#include <cstdlib>
#include <cmath>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <unordered_map>
#include <algorithm>
#define LT(x) (x * 2)
#define RT(x) (x * 2 + 1)

using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;

int n;
int a[100002];
vi b;   // 有序数组


int main() {
    //freopen("in.txt", "r", stdin);
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) {
        scanf("%d", &a[i]);
    }
    int m = (n + 1) / 2;
    b.push_back(a[0]);
    printf("%d\n", a[0]);
    for (int i = 1; i < m; ++i) {
        int pos = lower_bound(b.begin(), b.end(), a[i * 2 - 1]) - b.begin();
        b.insert(b.begin() + pos, a[i * 2 - 1]);
        pos = lower_bound(b.begin(), b.end(), a[i * 2]) - b.begin();
        b.insert(b.begin() + pos, a[i * 2]);
        printf("%d\n", b[i]);
    }
    return 0;
}
相关推荐
2301_8227032043 分钟前
Flutter 框架跨平台鸿蒙开发 - 创意声音合成器应用
算法·flutter·华为·harmonyos·鸿蒙
cmpxr_1 小时前
【C】数组名、函数名的特殊
c语言·算法
KAU的云实验台1 小时前
【算法精解】AIR期刊算法IAGWO:引入速度概念与逆多元二次权重,可应对高维/工程问题(附Matlab源码)
开发语言·算法·matlab
会编程的土豆1 小时前
【数据结构与算法】再次全面了解LCS底层
开发语言·数据结构·c++·算法
大熊背2 小时前
如何利用Lv值实现三级降帧
算法·自动曝光·lv·isppipeline
大尚来也2 小时前
驾驭并发:.NET多线程编程的挑战与破局之道
java·前端·算法
向阳而生,一路生花2 小时前
深入浅出 JDK7 HashMap 源码分析
算法·哈希算法
君义_noip3 小时前
信息学奥赛一本通 4150:【GESP2509七级】⾦币收集 | 洛谷 P14078 [GESP202509 七级] 金币收集
c++·算法·gesp·信息学奥赛·csp-s
摸个小yu3 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
汀、人工智能3 小时前
[特殊字符] 第93课:太平洋大西洋水流问题
数据结构·算法·数据库架构·图论·bfs·太平洋大西洋水流问题