跳到正文

个人记录

P3871 [TJOI2010] 中位数

xu_zhihao约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年7月10日
收录
2025年12月12日
更新
2026年10月1日
篇幅
约 1 分钟

版本

  1. v1当前

做法

  • 做法其实不难,但是使用 vector 的复杂度是假的,可以卡到 O(nmlog⁡n)O(nm \log n)。题目可以用 c++ 自带 rope 解决,其采用可持久化平衡树实现,相当于每一次操作的复杂度都是 O(log⁡n)O(\log n) 级别。接下去依据题意模拟即可,这里就不多赘述了。

参考代码

C++
#include<bits/stdc++.h>
#include <ext/rope>
using namespace __gnu_cxx;
using namespace std;
rope<int>v;
int a[200010];
int main(){
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
	    scanf("%d",&a[i]);
	    v.insert(upper_bound(v.begin(),v.end(),a[i])-v.begin(),a[i]);
    }
	int q;
	scanf("%d",&q);
	while(q--){
		string op;
		cin>>op;
		if(op=="add"){
			int A;
			scanf("%d",&A);
			n++;
			v.insert(upper_bound(v.begin(),v.end(),A)-v.begin(),A);
		}
		else{
			int mid=(n-1)/2;
			printf("%d\n",v[mid]);
		}
	}
	return 0;
} 
原文