题目:戳这里

百度之星初赛原题:戳这里

题意:n个不同的数,求中位数为m的区间有多少个。

解题思路:

此题的中位数就是个数为奇数的数组中,小于m的数和大于m的数一样多,个数为偶数的数组中,小于m的数比大于m的数少一。因此,维护比m小和比m大的数就行。

m~n进行处理,比m大的cnt++,比m小的cnt--,用vis数组记录每个cnt值的个数。

m~1再进行处理,比m大的cnt++,比m小的cnt--,ans+=vis[cnt]+vis[cnt+1],vis[cnt]可以理解为是右边有cnt个比m大的数的情况(n为奇数,vis[cnt+1]是右边有cnt个比m大的数的情况(n为偶数。(当然真正的数值并不代表这个意思,因为出现比m小的数时cnt--了,在这里形容是为了便于理解。

这样操作的意思是,先预处理[pos[m],r]的所有情况,在遍历[l,pos[m]]的所有情况时,直接求出答案。

代码比文字好理解:

 1 #include <bits/stdc++.h>
2 typedef long long ll;
3 const int maxn = 1e6+10;
4 const int inf = 0x3f3f3f3f;
5 const ll mod = 998244353;
6 using namespace std;
7 int a[maxn];
8 map<int,int>vis;
9 int main(){
10 int n, m;
11 scanf("%d %d", &n, &m);
12 int pos = 0;
13 for(int i = 1; i <= n; ++i) {
14 scanf("%d",a+i);
15 if(a[i] == m) pos = i;
16 }
17 int cnt = 0;
18 for(int i = pos; i <= n; ++i) {
19 if(a[i] > m) ++cnt;
20 if(a[i] < m) --cnt;
21 vis[cnt]++;
22 }
23 cnt = 0;
24 ll ans = 0;
25 for(int i = pos; i >= 1; --i) {
26 if(a[i] > m) --cnt;
27 if(a[i] < m) ++cnt;
28 ans += vis[cnt]+vis[cnt+1];//此时m左边的大小情况为cnt,要找右边为cnt和cnt+1的情况
29 }
30 printf("%lld\n", ans);
31 return 0;
32 }

最新文章

  1. iOS 之各种Crash
  2. CClayer ignoreAnchorPointForPosition 参数的作用
  3. ubuntu16.04下安装cuda8.0
  4. Linux乱码问题解决方案
  5. ps去水印
  6. apple mobile device服务无法启动,错误1053 解决
  7. jquery 展开折叠菜单
  8. 安装php时,make步骤报错make: *** [ext/gd/gd.lo] Error 1
  9. python中的builtin函数详解-第二篇
  10. python爬图
  11. Head First 设计模式 第6章 命令模式
  12. 队列(FIFO)—循环队列、队列的链式存储
  13. .NET Core 2.0迁移技巧之web.config配置文件
  14. HDU.5385.The path(构造)
  15. Ansible 简介
  16. 常见的HTTP报头(头参数)
  17. 用pt-stalk定位MySQL短暂的性能问题
  18. MikroTik RouterOS U盘安装工具netinstall的使用
  19. ASP.NET一个页面的生命周期
  20. appium定位方法

热门文章

  1. cursor pin s和cursor pin s wait on x
  2. 探索微软开源Python自动化神器Playwright
  3. 理解js闭包9大使用场景
  4. JS复习笔记一:冒泡排序和二叉树列
  5. css animation @keyframes 动画
  6. linux在终端中按下键盘立马反应
  7. Go Code Review Comments
  8. 死锁案例 GAP 锁 没有就插入,存在就更新
  9. (Oracle)取当前日期的最近工作日
  10. 系列trick - bitmask