C++构建最小堆

构建最小堆
Time Limit: 5000 MSMemory Limit: 1000 KB

Description

将数组按自下向上扫描,向下调整的方法,调整为最小堆

Input

第一行一个int型整数T(T<=10),代表一共有T组数据。
对于每组数据,输入一个整数n(n<=1000)和n个整数m(m<=1000)。

Output

输出T行, 每行包括一个序列, 代表该数组调整为最小堆后的序列。(每个相邻数据用空格隔开,每个序列结尾无多余的空格)

Sample Input

2
8 53 17 78 9 45 65 87 23
10 23 54 76 33 89 12 78 34 87 10

Sample Output

9 17 65 23 45 78 87 53
10 23 12 33 54 76 78 34 87 89

结果代码:

#include<iostream>
using namespace std;

int main()
{
	int T = 0;
	cin >> T;
	for (int t = 0; t < T; t++)
	{
		int n = 0;
		cin >> n;
		
		int MinHeap[2001];
		int pos = 0;
		for (int i = 0; i < n; i++)
		{
			int m = 0;
			cin >> m;
			MinHeap[i] = m;
			
			
		}
		for (int i = n; i < 2001; i++)
		{
			
			MinHeap[i] = 1000;


		}
		for (int i = n-1; i >= 0; i--)
		{ 
			int pos = i;
			MinHeap[i];
			if ((pos * 2 + 2) < n)
			{
				while ( MinHeap[pos * 2 + 1] <MinHeap[pos]|| MinHeap[pos * 2 + 2] < MinHeap[pos])
				{
					if (MinHeap[pos * 2 + 1] <= MinHeap[pos * 2 + 2])
					{
						int temp = MinHeap[pos];
						MinHeap[pos] = MinHeap[pos * 2 + 1];
						MinHeap[pos * 2 + 1] = temp;
						pos = pos * 2 + 1;
					}
					else
					{
						int temp = MinHeap[pos];
						MinHeap[pos] = MinHeap[pos * 2 + 2];
						MinHeap[pos * 2 + 2] = temp;
						pos = pos * 2 + 2;
					}
				}
				
			}
			else if ((pos * 2 + 1) < n)
			{
				if (MinHeap[pos * 2 + 1] < MinHeap[pos])
				{
					int temp = MinHeap[pos];
						MinHeap[pos] = MinHeap[pos * 2 + 1];
						MinHeap[pos * 2 + 1] = temp;
						
				}
			}

			
		}
		for (int i = 0; i < n; i++)
		{
			if (i != n - 1)cout << MinHeap[i] << " ";
			else cout << MinHeap[i] << endl;

		}
	}

	return 0;
}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

convK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值