zoukankan      html  css  js  c++  java
  • 106.动态中位数

    原题链接:106. 动态中位数


    解题思路

    对顶堆

    这是一个很有用的算法,具体思路大致是,开两个堆,一个是大根堆,一个是小根堆,然后小于中位数的都放在大根堆,大于中位数的都放在小根堆,如果说,一个堆的个数大于了当前序列的 1/2 ,那么就将多余的数移过去,直到两个堆数量相等。

    样例代码

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <cstring>
    #include <queue>
    #include <vector>
    using namespace std;
    struct cmp1
    {
        bool operator ()(int &a,int &b)
        {
            return a>b;
        }
    };
    priority_queue <int,vector<int>, cmp1> q1,kong1;
    priority_queue <int> q2,kong2;
    void init()
    {
        int t,x,n,now;
        cin>>t;
        while(t--)
        {
            cin>>x>>n;
            cout<<x<<" "<<(n+1)/2<<endl;
            q1=kong1;
            q2=kong2;
            int cnt=0;
            for (int i=1;i<=n;i++)
            {
                cin>>now;
                if(q1.empty())
                    q1.push(now);
                else
                {
                    if(now>q1.top()) 
                        q1.push(now);
                    else 
                        q2.push(now);
                    while(q1.size()<q2.size())
                    {
                        q1.push(q2.top());
                        q2.pop();
                    }
                    while(q1.size()>q2.size()+1)
                    {
                        q2.push(q1.top());
                        q1.pop();
                    }
                }
                if (i&1)
                {
                    cnt++;
                    cout<<q1.top()<<" ";
                    if (!(cnt%10))
                        cout<<endl;
                }
            }
            if (cnt%10)
                puts("");
        }
    }
    int main()
    {
        init();
        return 0;
    }
    
  • 相关阅读:
    spring中各个模块的作用
    《Spring实战》学习笔记-第四章:面向切面的Spring
    《Spring实战》学习笔记-第四章:面向切面的Spring
    Centos7下永久修改mysql5.6最大连接数
    Prefix-List
    Route-Map
    PBR Lab2
    Lab PBR
    ISIS超载位解决流量黑洞
    ISIS TLV
  • 原文地址:https://www.cnblogs.com/hnkjdx-ssf/p/14278738.html
Copyright © 2011-2022 走看看