P1627 [CQOI2009] 中位数

P1627 [CQOI2009] 中位数

小清新 trick 题。
题意:给你一个长度为 n 的排列,数 b,求中位数为 b 的子段个数。
容易想到,把 > b 的作为 1,< b 的作为 -1,最后统计包含 p 且和为 0 的子段个数。
用 map 维护一下左边不同和的个数,再往右扫一遍就做完了。

#include<bits/stdc++.h>
#define rep(i, a, b) for(int i = (a); i <= (b); ++ i)
#define per(i, a, b) for(int i = (a); i >= (b); -- i)
#define pb emplace_back
#define All(X) X.begin(), X.end()
using namespace std;
using ll = long long;
constexpr int N = 1e5 + 5;

int n, b, p, a[N], s;
ll ans;
map<int, int> mp;

int main() {
	ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
	cin >> n >> b;
	rep(i, 1, n) {
		cin >> a[i];
		if(a[i] == b) p = i;
	}
	mp[0] = 1;
	per(i, p - 1, 1) ++ mp[s += a[i] > b ? 1 : -1];
	s = 0;
	rep(i, p + 1, n) ans += mp[s += a[i] > b ? -1 : 1];
	cout << ans + mp[0];
	return 0;
}
posted @ 2024-01-30 15:03  Lu_xZ  阅读(7)  评论(0编辑  收藏  举报