You are given an integer sequence a1,a2,…,an
.
Find the number of pairs of indices (l,r)
( 1≤l≤r≤n) such that the value of median of al,al+1,…,ar is exactly the given number m.
The median of a sequence is the value of an element which is in the middle of the sequence after sorting it in non-decreasing order. If the length of the sequence is even, the left of two middle elements is used.
For example, if a=[4,2,7,5]
then its median is 4 since after sorting the sequence, it will look like [2,4,5,7] and the left of two middle elements is equal to 4. The median of [7,1,2,9,6] equals 6 since after sorting, the value 6will be in the middle of the sequence.
Write a program to find the number of pairs of indices (l,r)
( 1≤l≤r≤n) such that the value of median of al,al+1,…,ar is exactly the given number m.
The first line contains integers n
) — the length of the given sequence and the required value of the median.
The second line contains an integer sequence a1,a2,…,an
( 1≤ai≤2⋅105).
Print the required number.
5 4 1 4 5 60 4
8
3 1 1 1 1
6
15 2 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3
97
In the first example, the suitable pairs of indices are: (1,3)
/**
题意 给定长度为n的序列的子序列中 中位数为m的个数
思路: solved(n,m):表示中位数小于等于m的区间数 solved(n,m-1) :表示中位数小于等于m-1的区间的个数;
那么相减之后就是ans;
对于solve(n,m)的求法 可利用+1 -1 来进行运算
枚举右端点 计算 大于0 的数量 累加 树状数组维护即可;
*/
#include<bits/stdc++.h>
#define ll unsigned long long
using namespace std;
const int maxn=2e5+7;
int a[maxn],b[2*maxn];
struct node{
int c[maxn*2],n;
void init(int _n){
n=_n;
for(int i=0;i<=n;i++) c[i]=0;
}
void add(int st){
for(int i=st;i<=n;i+=i&-i) c[i]++;
}
int sum(int st){
int res=0;
for(int i=st;i>0;i-=i&-i) res+=c[i];
return res;
}
}tmp;
ll solved(int n,int m){
for(int i=1;i<=n;i++) b[i]=(a[i]<=m?1:-1);
for(int i=1;i<=n;i++) b[i]+=b[i-1];
tmp.init(n*2+1);
tmp.add(n+1);
ll res=0;
for(int i=1;i<=n;i++){
res+=tmp.sum(n+1+b[i]);
tmp.add(b[i]+n+1);
}
return res;
}
int main(){
int n,m;scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
printf("%I64d\n",solved(n,m)-solved(n,m-1));
return 0;
}