7-5 堆中的路径 两种思路,为什么一种行,一种不行

目录

第一种

第二种

解释


投票选项在最后面

第一种

#include<iostream>
using namespace std;
//数据结构
#define element int
typedef struct Heap {
	element* data;
	int size;
}heap;
void tiletheap(heap& l_heap, int i);
void sortheap(heap& l_heap);
void swap(int* a, int* b);
void sortheap(heap& l_heap) {
	for (int i = l_heap.size / 2; i > 0; i--) {
		tiletheap(l_heap, i);
	}
}
void swap(int* a, int* b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}
void tiletheap(heap& l_heap,int i) {
	int mix_data = i;
	int left = i * 2 ;
	int right = i * 2 + 1;
	if (left <= l_heap.size && l_heap.data[left] < l_heap.data[mix_data]) {
		mix_data = left;
	}
	if (right <= l_heap.size && l_heap.data[right] < l_heap.data[mix_data]) {
		mix_data = right;
	}
	if (mix_data != i) {
		swap(&l_heap.data[mix_data], &l_heap.data[i]);
		tiletheap(l_heap, mix_data);
	}
}


int main() {
	int N, M, j;
	cin >> N >> M;
	heap* littleHeap = new heap;
	littleHeap->size = N;
	littleHeap->data = new element[N+1];
	for (int i = 1; i <= N; i++) {
		cin >> littleHeap->data[i];
	}
	sortheap(*littleHeap);
	for (int i = 0; i < M; i++) {
		int index;
		cin >> index;
		cout << littleHeap->data[index];
		index = index / 2;
		while (index != 0) {
			cout << " ";
			cout << littleHeap->data[index];
			index = index / 2;
		}
		cout << endl;
	}
	return 0;
}

第二种

#include<iostream>
using namespace std;
//数据结构
#define element int
typedef struct Heap {
	element* data;
	int size;
}heap;
void swap(int* a, int* b) {
	int temp = *a;
	*a = *b;
	*b = temp;
}
void insert(heap& l_heap, int x,int i) {
	l_heap.data[i] = x;
	while (i / 2)
	{
        if(l_heap.data[i] < l_heap.data[i / 2])
		swap(l_heap.data[i], l_heap.data[i / 2]);
		i/=2;
	}
}
int main() {
	int N, M;
	cin >> N >> M;
	heap* littleHeap = new heap;
	littleHeap->size = N;
	littleHeap->data = new element[N+1];
	for (int i = 1; i <= N; i++) {
		int x;
		cin >> x;
		insert(*littleHeap, x, i);
	}
	for (int i = 0; i < M; i++) {
		int index;
		cin >> index;
		cout << littleHeap->data[index];
		index = index / 2;
		while (index != 0) {
			cout << " ";
			cout << littleHeap->data[index];
			index = index / 2;
		}
		cout << endl;
	}
	return 0;
}

解释

第一种是你先都给我,然后排。

第二种是给一个我排一个。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

每天写bug的屑闲鱼

请我杯饮料吧

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

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

打赏作者

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

抵扣说明:

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

余额充值