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;
}
相关推荐
foundbug99921 分钟前
Polar Code 编解码 MATLAB 实现
开发语言·算法·matlab
李小小钦27 分钟前
D. Storming Arasaka(Codeforces 2238)
c语言·开发语言·数据结构·c++·算法
技术不好的崎鸣同学40 分钟前
[ACTF2020 新生赛]Include 思路及解法
算法·安全·web安全
先吃饱再说1 小时前
一篇吃透树的遍历:递归与迭代的完整拆解
数据结构·算法
Robot_Nav1 小时前
贪心算法、动态规划与 MPPI 算法结构相关力扣题目汇总
算法·贪心算法·动态规划
战族狼魂2 小时前
每日一课:算法系统学习路线
人工智能·算法·大模型·大语言模型
变量未定义~2 小时前
连通块中点的数量、堆箱子(4星)
算法
j7~2 小时前
【算法】专题二:滑动窗口之水果成蓝,找到字符串中所有字⺟异位词等算法题
c++·算法·滑动窗口·水果成蓝·最小字串覆盖·优选算法精选
木木子222 小时前
# 星座配对深度解析:Select 长列表选择器、矩阵评分算法与数据驱动建议
java·算法·华为·矩阵·harmonyos
大鱼>3 小时前
AI+货物追踪:跨境电商包裹追踪系统
人工智能·深度学习·算法·机器学习