2 solutions

  • 2
    @ 2025-3-21 21:32:05

    更简洁的中位对顶堆写法

    #include<bits/stdc++.h>
    using namespace std;
    template<typename T>
    class d_heap
    {
    	private:
    		#define pq priority_queue
    		pq<T>big;
    		pq<T,vector<T>,greater<T> >small;
    		#undef pq
    		void ph()//左右平衡 
    		{
    			if(big.size()<small.size())
    				big.push(small.top()),small.pop();
    			if(big.size()-small.size()>1)
    				small.push(big.top()),big.pop();
    		}
    	public:
    		void push(T x)
    		{
    			if(small.size() && x>small.top())small.push(x);
    			else big.push(x);
    			ph();
    		}
    		T top()
    		{
    			return big.top();
    		}
    };
    d_heap<int>q;
    int main()
    {
    	int n;
    	cin>>n;
    	for(int i=1;i<=n;i++)
    	{
    		int x;cin>>x;
    		q.push(x);
    		if(i%2)
    			cout<<q.top()<<"\n";
    	}
    	return 0;
    }
    

    vector+二分写法

    #include<bits/stdc++.h>
    using namespace std;
    vector<int>v;
    int main()
    {
    	int n;
    	cin>>n;
    	for(int i=1;i<=n;i++)
    	{
    		int x;cin>>x;
    		v.insert(upper_bound(v.begin(),v.end(),x),x);
    		if(i%2)
    			cout<<v[v.size()/2]<<"\n";
    	}
    	return 0;
    }
    

    Information

    ID
    365
    Time
    1000ms
    Memory
    128MiB
    Difficulty
    7
    Tags
    # Submissions
    42
    Accepted
    9
    Uploaded By