题解 | #【模板】堆#

【模板】堆

https://www.nowcoder.com/practice/13f61c8c92404f5ea5d6fa4c692869fb

#include <iostream>
using namespace std;
const int N = 1e5+10;
int n,x;
string s;
int h[N];

void down(int u,int num)
{
	int t = u;
	if(2*u <= num && h[t] < h[2*u]) t = 2*u;
	if(2*u+1 <= num && h[t] < h[2*u+1]) t = 2*u+1;
	if(u != t)
	{
		swap(h[t],h[u]);
		down(t,num);
	}
}

void up(int u)
{
	while(u / 2 && h[u/2] < h[u])
	{
		swap(h[u/2],h[u]);
		u /= 2;
	}
}

int main()
{
    int size = 0;
	cin>>n;
	while(n--)
	{
		cin>>s;
		if(s == "push")
		{
			cin>>x;
			++size;
			h[size] = x;
			up(size);
		}
		else if(s == "top")
		{
			if(size == 0) cout << "empty" << endl;
			else cout << h[1] << endl;
		}
		else
		{
			if(size == 0) cout << "empty" << endl;
			else
			{
				cout << h[1] << endl;
				h[1] = h[size];
				size--;
				down(1,size);
			}
		}
	}
	return 0;
 }

全部评论

相关推荐

点赞 评论 收藏
分享
Rac000n:淘天-客户运营部-AI研发工程师,智能客服方向,暑期实习招聘,欢迎联系
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务