Median on Segments (Permutations Edition)
time limit per test
3 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given a permutation n occurs exactly once in the sequence.

Find the number of pairs of indices m.

The median of a sequence is the value of the 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 6 will be in the middle of the sequence.

Write a program to find the number of pairs of indices m.

Input

The first line contains integers 1≤m≤n) — the length of the given sequence and the required value of the median.

The second line contains a permutation p exactly once.

Output

Print the required number.

Examples
input
Copy
5 4
2 4 5 3 1
output
Copy
4
input
Copy
5 5
1 2 3 4 5
output
Copy
1
input
Copy
15 8
1 15 2 14 3 13 4 8 12 5 11 6 10 7 9
output
Copy
48
Note

In the first example, the suitable pairs of indices are: (2,4).

 

题意:给你n个数和m,问在这n个数中以m为中位数的区间有多少个?

因为要使m为中位数,肯定是m的值位于这些数的中间的部分,即要有比m大的数和比m小的数,且大的数和小的数要相等或者大的数比小的数多一

#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <vector>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#define debug(a) cout << #a << " " << a << endl
using namespace std;
const int maxn = 2e5 + 10;
const int mod = 1e9 + 7;
typedef long long ll;
ll a[maxn], vis[maxn];
int main() {
    ll n, m;
    while( cin >> n >> m ) {
        map<ll,ll> mm;
        ll  pos;
        for( ll i = 1; i <= n; i ++ ) {
            cin >> a[i];
            if( a[i] == m ) {
                pos = i;
            }
        }
        ll cnt = 0;
        for( ll i = pos; i <= n; i ++ ) {
            if( a[i] > m ) {
                cnt ++;
            } else if( a[i] < m ) {
                cnt --;
            }
            mm[cnt] ++;
        }
        ll ans = 0;
        cnt = 0;
        for( ll i = pos; i >= 1; i -- ) {
            if( a[i] > m ) {
                cnt ++;
            } else if( a[i] < m ) {
                cnt --;
            }
            ans += mm[-cnt];
            ans += mm[1-cnt];  //个数为偶数,中位数在中间两位的左边一位
        }
        cout << ans << endl;
    }
    return 0;
}

 

相关文章:

  • 2021-07-29
  • 2022-12-23
  • 2021-09-26
  • 2022-01-23
  • 2022-12-23
  • 2021-11-15
  • 2022-12-23
  • 2021-05-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
  • 2022-01-13
  • 2022-12-23
相关资源
相似解决方案