Codeforces Round #496 (Div. 3 ) E1. Median on Segments (Permutations Edition)(中位数计数)
You are given a permutation?p1,p2,…,pnp1,p2,…,pn. A permutation of length?nn?is a sequence such that each integer between?11?and?nn?occurs exactly once in the sequence.
Find the number of pairs of indices?(l,r)(l,r)?(1≤l≤r≤n1≤l≤r≤n) such that the value of the median of?pl,pl+1,…,prpl,pl+1,…,pr?is exactly the given number?mm.
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?a=[4,2,7,5]a=[4,2,7,5]?then its median is?44?since after sorting the sequence, it will look like?[2,4,5,7][2,4,5,7]?and the left of two middle elements is equal to?44. The median of?[7,1,2,9,6][7,1,2,9,6]?equals?66?since after sorting, the value?66?will be in the middle of the sequence.
Write a program to find the number of pairs of indices?(l,r)(l,r)?(1≤l≤r≤n1≤l≤r≤n) such that the value of the median of?pl,pl+1,…,prpl,pl+1,…,pr?is exactly the given number?mm.
InputThe first line contains integers?nn?and?mm?(1≤n≤2?1051≤n≤2?105,?1≤m≤n1≤m≤n) — the length of the given sequence and the required value of the median.
The second line contains a permutation?p1,p2,…,pnp1,p2,…,pn?(1≤pi≤n1≤pi≤n). Each integer between?11?and?nn?occurs in?pp?exactly once.
OutputPrint the required number.
Examples input Copy 5 42 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:?(1,3)(1,3),?(2,2)(2,2),?(2,3)(2,3)?and?(2,4)(2,4).
?
?
題意:給出n個數,中位數m,求在這n個數中的任意區間內中位數是n的個數,區間個數是偶數的時候去左邊的為?中位數
解題思路:剛開始我以為這是主席樹的模板題,第k大,后來聽別人說不用這么復雜,因為是n個數互不重復1-n,因為要求的區間里面肯定包含了m,所以我們先求出m的位置,然后我們仔細想?
可以得知在這個區間里面要使中位數是m的話,奇數區間大于m的個數與小于m的個數是一樣的,偶數區間是大于m的個數比小于m的個數多1,所以我們用map記錄比m大和小的個數,我們先從
m的位置從右邊遍歷求出區間大于小于m的情況,用map 存大于m和小于m的差值,這樣比較方便,比如mp[0]=1,說明右邊大于m和小于m的區間個數相等的區間有1個,比如mp[-1]=2,說明右邊
大于m比小于m少一個的區間個數有2個,以此類推,然后我們再此遍歷左邊,如果左邊大于m的個數是1的話,奇數區間那么我就要右邊小于m的個數為1,也就是mp[-1],偶數區間就要右邊大于m
小于m個數相等,也就是mp[0],從而推出式子? cnt記錄大于小于m的個數 sum=sum+mp[-cnt]+mp[1-cnt];
#include<cstdio> #include<iostream> #include<map> using namespace std; typedef long long ll; int main() {map<ll,ll> mp;ll m,n,a[200005];cin>>n>>m;int pos;for(int i=0;i<n;i++){cin>>a[i];if(a[i]==m)pos=i;}int cnt=0;for(int i=pos;i<n;i++){if(a[i]>m) cnt++;if(a[i]<m) cnt--;mp[cnt]++;}ll sum=0;cnt=0;for(int i=pos;i>=0;i--){if(a[i]>m) cnt++;if(a[i]<m) cnt--;sum=sum+mp[-cnt]+mp[1-cnt];}cout<<sum; }?
轉載于:https://www.cnblogs.com/Lis-/p/9299800.html
總結
以上是生活随笔為你收集整理的Codeforces Round #496 (Div. 3 ) E1. Median on Segments (Permutations Edition)(中位数计数)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: equals与hashcode的区别与联
- 下一篇: 《HBase权威指南》读书笔记(二)