【题目链接】
【算法】
将小于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*2],r[MAXN*2]; template <typename T> inline void read(T &x) { long long f = 1; x = 0; char c = getchar(); for (; !isdigit(c); c = getchar()) { if (c == '-') f = -f; } for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0'; x *= f; } template <typename T> inline void write(T x) { if (x < 0) { putchar('-'); x = -x; } if (x > 9) write(x/10); putchar(x%10+'0'); } template <typename T> inline void writeln(T x) { write(x); puts(""); } int main() { read(n); read(m); for (i = 1; i <= n; i++) { read(a[i]); if (a[i] == m) pos = i; } sum = 0; for (i = pos - 1; i >= 1; i--) { if (a[i] < m) opt = -1; else opt = 1; sum += opt; l[sum+n]++; } sum = 0; for (i = pos + 1; i <= n; i++) { if (a[i] < m) opt = -1; else opt = 1; sum += opt; r[sum+n]++; } ans = l[n] + r[n] + 1; for (i = 0; i <= 2 * n; i++) ans += l[i] * r[2*n-i]; writeln(ans); return 0; }