1. 程式人生 > >Codeforces #496 E1. Median on Segments (Permutations Edition)

Codeforces #496 E1. Median on Segments (Permutations Edition)

scanf media long long ati tail ack pos color article

http://codeforces.com/contest/1005/problem/E1 題目

https://blog.csdn.net/haipai1998/article/details/80985281 原博客

對樣例1:

5 4
2 4 5 3 1

m=4,所以下標pos=2; 從pos往右遇到比m大的就cnt++,遇到小的就cnt--: 剛開始cnt=0; mp[cnt]++

於是從pos開始到 n: mp[0]=1, mp[1]=1, mp[0]=2 , mp[-1]=1;

接下來從pos向左, 遇到比m大的就cnt-- ,遇到比小的就cnt++ , 剛開始cnt=0

因為n為偶數時m要排在n/2 ,n為奇數時m要排在n/2+1;

所以 ans += mp[cnt] + mp[cnt+1] 比如i=pos時候,此時cnt=0, ans+=mp[0]+mp[1] (偶數的情況加上奇數的情況)

i=pos-1,即cnt=1,a[i]=2的時候,ans+=mp[1]+mp[2] (mp[1]即加到5的位置)

 1 #include<iostream>
 2 #include<cstdio>
 3 #include <cctype>
 4 #include<algorithm>
 5 #include<cstring>
 6 #include<cmath>
 7
#include<string> 8 #include<cmath> 9 #include<set> 10 #include<vector> 11 #include<stack> 12 #include<queue> 13 #include<map> 14 using namespace std; 15 #define ll long long 16 #define mem(a,x) memset(a,x,sizeof(a)) 17 #define se second 18 #define fi first 19
const int INF= 0x3f3f3f3f; 20 const int N=2e5+5; 21 22 int n,m,pos,a[N]; 23 map<int,ll> mp; 24 25 int main() 26 { 27 cin>>n>>m; 28 for(int i=1;i<=n;i++){ 29 scanf("%d",&a[i]); 30 if(a[i]==m) pos=i; 31 } 32 int num=0,cnt=0; 33 for(int i=pos;i<=n;i++) 34 { 35 if(a[i]>m) cnt++; 36 if(a[i]<m) cnt--; 37 mp[cnt]++; 38 } 39 num=0,cnt=0; 40 ll ans=0; 41 for(int i=pos;i>=1;i--) // 2 4 5 3 1 42 { 43 if(a[i]<m) cnt++; 44 if(a[i]>m) cnt--; 45 ans+=mp[cnt]+mp[cnt+1]; 46 } 47 cout<<ans; 48 }

Codeforces #496 E1. Median on Segments (Permutations Edition)