【题目链接】
【算法】
将小于m的数看作-1,大于m的看作1
然后求前缀和,如果区间[l,r]的中位数是m,显然有 : sum(r) - sum(l-1) = 0
因此,只需m的位置之前(后)统计每个前缀和出现的次数,然后通过乘法原理计算答案,即可
【代码】
#include<bits/stdc++.h>
using namespace std;
#define MAXN 100010 long long i,n,m,pos,sum,opt,ans;
long long a[MAXN],l[MAXN*],r[MAXN*]; template <typename T> inline void read(T &x) {
long long f = ; x = ;
char c = getchar();
for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; }
for (; isdigit(c); c = getchar()) x = (x << ) + (x << ) + c - '';
x *= f;
}
template <typename T> inline void write(T x) {
if (x < ) { putchar('-'); x = -x; }
if (x > ) write(x/);
putchar(x%+'');
}
template <typename T> inline void writeln(T x) {
write(x);
puts("");
} int main() { read(n); read(m);
for (i = ; i <= n; i++) {
read(a[i]);
if (a[i] == m) pos = i;
}
sum = ;
for (i = pos - ; i >= ; i--) {
if (a[i] < m) opt = -;
else opt = ;
sum += opt;
l[sum+n]++;
}
sum = ;
for (i = pos + ; i <= n; i++) {
if (a[i] < m) opt = -;
else opt = ;
sum += opt;
r[sum+n]++;
}
ans = l[n] + r[n] + ;
for (i = ; i <= * n; i++) ans += l[i] * r[*n-i]; writeln(ans); return ; }