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;
}
相关推荐
AllData公司负责人40 分钟前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康2 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长2 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David3 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck5 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T6 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊6 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
AAA修煤气灶刘哥8 小时前
我都切到下一张图了,Agent 怎么还在解释上一张?
人工智能·算法·架构
Navigator_Z8 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
青少儿编程课堂10 小时前
蓝桥杯青少组图形化真题:校园无人机编队灯光秀解析(全国青少年信息素养大赛·电子学会12月图形化考级同源考点)
c++·python·算法·bfs·信息学竞赛