Loading

代码仓库2: 对顶堆,对顶栈

对顶栈:

class MinStack {
public:
    
    stack<int> st1;
    stack<int> stmin;
    
    MinStack() {
        
    }
    
    void push(int x) {
        st1.push(x);
        if(stmin.empty()||stmin.top()>=x) stmin.push(x);
    }
    
    void pop() {
        if(st1.top()==stmin.top()) stmin.pop();
        st1.pop();
    }
    
    int top() {
        return st1.top();
    }
    
    int getMin() {
        return stmin.top();
    }
};

/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(x);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

对顶堆:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<sstream>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<deque>
#include<cstdlib>
#include<ctime>
#define dd double
#define ld long double
#define ll long long
#define ull unsigned long long
#define N 10000
#define M number
using namespace std;

struct cmp1{
	inline bool operator () (int a,int b){
		return a<b;
	}
};
priority_queue<int,vector<int>,cmp1> q1;//big
struct cmp2{
	inline bool operator () (int a,int b){
		return a>b;
	}
};
priority_queue<int,vector<int>,cmp2> q2;//small

int size1,size2,all,tot,hao;
int n,a[N],m;

int main(){
	scanf("%d",&m);
	while(m--){
		while(!q1.empty()) q1.pop();
		while(!q2.empty()) q2.pop();
		n=0;memset(a,0,sizeof(a));
		size1=size2=all=tot=hao=0;
		scanf("%d%d",&hao,&n);
		if(hao!=1) printf("\n");
		printf("%d %d\n",hao,n+1>>1);
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
			int now1=0,now2=0;
			if(!q1.empty()) now1=q1.top();
			if(!q2.empty()) now2=q2.top();
			all++;
			if(a[i]<=now1) q1.push(a[i]),size1++;
			else q2.push(a[i]),size2++;
			if(!q1.empty()) now1=q1.top();
			if(!q2.empty()) now2=q2.top();
			if(all%2==0){
				if(size1>size2) q2.push(now1),q1.pop(),size1--,size2++;
				else if(size1<size2) q1.push(now2),q2.pop(),size2--,size1++;
			}
			else{
				if(size1<size2) q1.push(now2),q2.pop(),size2--,size1++;
				int ans=q1.top();tot++;
				if(tot==11) printf("\n"),tot=1;
				printf("%d ",ans);
			}
		}
	}
	return 0;
}
posted @ 2021-03-01 21:17  hyl天梦  阅读(51)  评论(0编辑  收藏  举报