POJ 1442 Black Box(堆实现)

/*
题意:ADD(a)表示向集合中增加元素a,get表示取出第k小元素,k根据get出现的次数不断变化,出现多少次取第几小数

题解:每次取第k小元素,k不断更新。使用两个堆,来完成。
小顶堆负责,选出最小的元素
大顶堆负责,选出k个元素中最大的元素,即第k小元素
*/

#include <iostream>
using namespace std;
const int nMax = 30010;
int tree1[nMax];//大顶堆
int k1;
int tree2[nMax];//小顶堆
int k2;
int M, N;
int A[nMax];

void build1(int *tree, int k)
{
	int p = k;
	while(p != 1)
	{
		if(tree[p] > tree[p / 2])
		{
			int temp = tree[p];
			tree[p] = tree[p / 2];
			tree[p / 2] = temp;
		}
		p = p / 2;
	}
}

void build2(int *tree, int k)
{
	int p = k;
	while(p != 1)
	{
		if(tree[p] < tree[p / 2])
		{
			int temp = tree[p];
			tree[p] = tree[p / 2];
			tree[p / 2] = temp;
		}
		p = p / 2;
	}
}

void update1(int *tree, int k)
{
	int p = 1;
	while(2 * p <= k)
	{
		int son;
		if(2 * p == k || tree[2 * p] > tree[2 * p + 1])
			son = 2 * p;
		else
			son = 2 * p + 1;
		if(tree[p] < tree[son])
		{
			int temp = tree[p];
			tree[p] = tree[son];
			tree[son] = temp;
		}
		p = son;
	}
}

void update2(int *tree, int k)
{
	int p = 1;
	while(2 * p <= k)
	{
		int son;
		if(2 * p == k || tree[2 * p] < tree[2 * p + 1])
			son = 2 * p;
		else
			son = 2 * p + 1;
		if(tree[p] > tree[son])
		{
			int temp = tree[p];
			tree[p] = tree[son];
			tree[son] = temp;
		}
		p = son;
	}
}

int main()
{
	//freopen("e://data.in", "r", stdin);
	while(scanf("%d%d", &M, &N) != EOF)
	{
		int i;
		for(i = 1; i <= M; ++ i)
			scanf("%d", &A[i]);
		int pre = 0;
		k1 = k2 = 0;
		for(i = 1; i <= N; ++ i)
		{
			int a;
			scanf("%d", &a);
			for(int j = pre + 1; j <= a; ++ j)
			{
				tree2[++k2] = A[j];
				build2(tree2, k2);
				
			}
			pre = a;
			tree1[++ k1] = tree2[1];
			build1(tree1, k1);
			tree2[1] = tree2[k2 --];
			update2(tree2, k2);
			while(k2 != 0 && tree1[1] > tree2[1])
			{
				int temp = tree1[1];
				tree1[1] = tree2[1];
				tree2[1] = temp;
				update1(tree1, k1);
				update2(tree2, k2);
			}
			printf("%d\n", tree1[1]);
		}
		
		
	}
	return 0;
}

你可能感兴趣的:(tree,Build)