题意分析
比
k
k
小权值为-1,比大权值为1。
以
k
k
<script type="math/tex" id="MathJax-Element-6">k</script>为中心,向左向右算个前缀和,统计一下个数,统计时别忘了shift。
然后从左查询,右区间查询为0的即可。
代码总览
#include <bits/stdc++.h>
#define rep(i,a,b) for (int i = a; i<=b; ++i)
using namespace std;
const int nmax = 1e5 + 100;
const int INF = 0x3f3f3f3f;
const int shift = 1e5;
typedef long long ll;
typedef double db;
int a[nmax], tag[nmax], Lcnt[nmax << 1], Rcnt[nmax << 1], Lprefix[nmax], Rprefix[nmax];
int n, k, pos;
int main() {
scanf("%d %d", &n, &k);
rep(i, 1, n) scanf("%d", &a[i]);
rep(i, 1, n) {
if (a[i] < k) tag[i] = -1;
else if (a[i] == k) tag[i] = 0, pos = i;
else tag[i] = 1;
}
int ans = 1;
int sum = 0; Lcnt[0 + shift] = Rcnt[0 + shift] = 1;
for (int i = pos - 1; i >= 1; --i) {
sum += tag[i]; Lprefix[i] = sum;
Lcnt[sum + shift] ++;
}
sum = 0;
rep(i, pos + 1, n) {
sum += tag[i]; Rprefix[i] = sum;
Rcnt[sum + shift]++;
}
if (pos == 1) {
rep(i, 2, n) ans += Lcnt[-Rprefix[i] + shift];
} else if (pos == n) {
rep(i, 1, n - 1) ans += Rcnt[-Lprefix[i] + shift];
} else {
rep(i, 1, pos - 1) ans += Rcnt[-Lprefix[i] + shift];
rep(i, pos + 1, n) if (Rprefix[i] == 0) ans++;
}
printf("%d\n", ans);
return 0;
}