思路:用一个大根堆和一个小根堆,小根堆存排名m/2+1~m的元素,大根堆存排名1~m/2的元素,
中位数就是大根堆的堆顶元素。
每来一个新的数,如果比中位数小就插入大根堆,不然就插入小根堆。插入完后要保证大根堆的元素个数比小根堆大1。
最后输出中位数。
代码:
- #include
- #include
- #include
- #include
- using namespace std;
- int n;
- priority_queue<int,vector<int>,greater<int>>heap;
- priority_queue<int,vector<int>,less<int>>heap1;
- const int N=1e5+100;
- int a[N];
- int main()
- {
- int t;
- cin>>t;
- for(int j=1;j<=t;j++)
- {
- priority_queue<int,vector<int>,greater<int>>heap;//右半边
- priority_queue<int,vector<int>,less<int>>heap1;//左半边
- int p,n;
- cin>>p>>n;
- for(int i=1;i<=n;i++)
- scanf("%d",&a[i]);
-
- cout<
' '<2+1<
- int cnt=0;
- for(int i=1;i<=n;i++)
- {
- if(heap1.size()&&a[i]<=heap1.top())
- heap1.push(a[i]);
- else if(heap1.size()==0)
- heap1.push(a[i]);
- else if(heap1.size()&&a[i]>heap1.top())
- heap.push(a[i]);
-
- while(heap1.size()<=heap.size())
- {
- heap1.push(heap.top());
- heap.pop();
- }
- while(heap1.size()>=heap.size()+2)
- {
- heap.push(heap1.top());
- heap1.pop();
- }
- if(i%2)
- {
- cnt++;
-
- cout<
top()<<' '; - if(cnt%10==0&&i!=n)
- cout<
- }
- }
- if(j!=t)
- cout<
- }
- return 0;
- }
-
相关阅读:
OOP 向量加减(友元+拷贝构造)
内网穿透frp简单安装
基于JAVA+SpringBoot+Mybatis+MYSQL的销售团队管理系统
Linux上通过mysqldump命令实现自动备份
RocketMq开启安全认证ACL-解决服务器系统安全漏洞
CAS:190598-55-1_Biotin sulfo-N-hydroxysuccinimide ester生物素化试
线性回归(linear regression)
Java泛型方法与普通成员方法以及案例说明(五)
时空智友企业流程化管控系统任意文件上传漏洞复现【附POC】
SaaSBase:什么是Flomo?
-
原文地址:https://blog.csdn.net/m0_62327332/article/details/126393214