BZOJ 1303: [CQOI2009]中位数图
刚开始以为有多个b,自闭了好一会儿
从b所在那个位置开始,分别往左往右
定义一个临时变量$tmp$
遇到$>b 的 就+1, 遇到<b的就-1$
$那么左边的tmp 肯定能够和 右边的-tmp 匹配使得这一段区间中b是中位数$
1 #include <bits/stdc++.h> 2 using namespace std; 3 4 #define ll long long 5 #define N 100010 6 int n, b, a[N]; 7 int cntl[N << 1], cntr[N << 1]; 8 9 void Run() 10 { 11 while (scanf("%d%d", &n, &b) != EOF) 12 { 13 int pos = -1; 14 for (int i = 1; i <= n; ++i) 15 { 16 scanf("%d", a + i); 17 if (a[i] == b) pos = i; 18 } 19 for (int i = pos - 1, tmp = 0; i >= 1; --i) 20 { 21 if (a[i] > b) ++tmp; 22 else if (a[i] < b) --tmp; 23 ++cntl[tmp + N]; 24 } 25 for (int i = pos + 1, tmp = 0; i <= n; ++i) 26 { 27 if (a[i] > b) ++tmp; 28 else if (a[i] < b) --tmp; 29 ++cntr[tmp + N]; 30 } 31 ll res = (cntl[N] + 1) * (cntr[N] + 1); 32 for (int i = 1; i <= n; ++i) 33 res += cntl[N + i] * cntr[N - i] + cntl[N - i] * cntr[N + i]; 34 printf("%lld\n", res); 35 } 36 } 37 38 int main() 39 { 40 #ifdef LOCAL 41 freopen("Test.in", "r", stdin); 42 #endif 43 44 Run(); 45 return 0; 46 }