目录
投票选项在最后面
第一种
#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;
}
解释
第一种是你先都给我,然后排。
第二种是给一个我排一个。