跳到正文

题解

题解:AT_abc458_d [ABC458D] Chalkboard Median

wcy110614约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年5月19日
收录
2026年8月4日
更新
2026年11月15日
篇幅
约 2 分钟

版本

  1. v1当前

打个 abc,给自己唐笑了。

最开始有一个数,每次添加两个数,之后求数列中位数。

给个简单做法,维护一个 set 和一根指针,指针指向中位数。

考虑指针每次添加两个数之后会怎么变化。

  1. 两个数都大于指针指向的数:指针指向的数就在中位数靠左一位,指针右移一位。

  2. 两个数一个大于指针指向的数,一个小于指针指向的数:指针指向的数依然是中位数。

  3. 两个数都小于指针指向的数:指针指向的数就在中位数靠右一位,指针左移一位。

维护好就行了,每次输出操作后指针指向的数。

C++
#include <bits/stdc++.h>
#define E(i, l, r) for(int i = l; i <= r; ++ i)
using namespace std;
using ll = long long;
int tt;
namespace p192 {
	const int N = 1E6 + 10;
	int x, q, a, b;
	multiset <int> s;
	inline void Main () {
		cin >> x;
		s.emplace(x);
		auto IT = s.lower_bound(x);
		cin >> q;
		while(q --) {
			cin >> a >> b;
			s.emplace(a), s.emplace(b);
			if(a > *IT && b > *IT) ++ IT;
			else if(a < *IT && b < *IT) -- IT;
			cout << *IT << "\n";
		}
		return void();
	}
}
int main() {
	tt = 1;
	while(tt --) p192::Main();
	return 0;
}
原文