C++ 通过构建heap得到不同的答案一个是通过insertKey,另一个是通过buildHeap
我只是试着建立一个最小堆,我得到了建立一个堆的不同答案 方法1将元素插入数组,然后调用build-minheap方法,该方法在内部节点上应用minHeapify 方法2通过在每个点检查数组是否遵循minheap属性,将元素直接插入堆中 我想这两个答案都是正确的,但是如果某个测试用例显示一个顺序,而ans是不同的,可以吗C++ 通过构建heap得到不同的答案一个是通过insertKey,另一个是通过buildHeap,c++,binary-heap,C++,Binary Heap,我只是试着建立一个最小堆,我得到了建立一个堆的不同答案 方法1将元素插入数组,然后调用build-minheap方法,该方法在内部节点上应用minHeapify 方法2通过在每个点检查数组是否遵循minheap属性,将元素直接插入堆中 我想这两个答案都是正确的,但是如果某个测试用例显示一个顺序,而ans是不同的,可以吗 #include<iostream> #include<cmath> #include<vector> using namespace std
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
int leftChild(int i)
{
return (2*i+1);
}
int rightChild(int i)
{
return (2*i+2);
}
int parent(int i)
{
return ((i-1)/2);
}
void minHeapify(vector<int> &a,int i)
{
int smallest = i;
int l = leftChild(i);
int r = rightChild(i);
if(l < a.size() && a[l] < a[i])
smallest = l;
if(r < a.size() && a[r] < a[smallest])
smallest = r;
if(smallest != i)
{
swap(a[smallest],a[i]);
minHeapify(a,smallest);
}
}
void buildMinHeap(vector<int> &a)
{
for(int i = a.size()/2 - 1 ; i >= 0 ; i--)
minHeapify(a,i);
}
void insertKey(vector<int> &b,int new_val,int* n)
{
*n = *n + 1;
int i = *n - 1;
b[i] = new_val;
while(i!=0 && b[i] < b[parent(i)])
{
swap(b[i],b[parent(i)]);
i = parent(i);
}
}
void printline()
{
cout<<"********************************************************************"<<endl;
}
int main()
{
cout<<"Enter the elements in the array for building a min heap"<<endl;
vector<int> a;
a.push_back(2);
a.push_back(16);
a.push_back(74);
a.push_back(58);
a.push_back(36);
a.push_back(4);
a.push_back(28);
a.push_back(15);
a.push_back(35);
a.push_back(82);
a.push_back(6);
//One thing you can do is make a normal array and build a heap out of it in O(n) time
buildMinHeap(a);
for(int i=0;i<a.size();i++)
cout<<a[i]<<" ";
cout<<endl<<endl;
printline();
//Or second method is insert in a way such that it is always inserted in a form of heap.
vector<int> b(10000);
int heapsize = 0;
insertKey(b,2,&heapsize);
insertKey(b,16,&heapsize);
insertKey(b,74,&heapsize);
insertKey(b,58,&heapsize);
insertKey(b,36,&heapsize);
insertKey(b,4,&heapsize);
insertKey(b,28,&heapsize);
insertKey(b,15,&heapsize);
insertKey(b,35,&heapsize);
insertKey(b,82,&heapsize);
insertKey(b,6,&heapsize);
for(int i=0;i<heapsize;i++)
cout<<b[i]<<" ";
}
#包括
#包括
#包括
使用名称空间std;
int leftChild(int i)
{
返回(2*i+1);
}
int rightChild(int i)
{
返回(2*i+2);
}
int父级(int i)
{
返回((i-1)/2);
}
void minHeapify(向量&a,整数i)
{
int=i;
int l=leftChild(i);
int r=右子女(i);
如果(l=0;i--)
minHeapify(a,i);
}
void insertKey(向量&b,整数新值,整数*n)
{
*n=*n+1;
int i=*n-1;
b[i]=新值;
而(i!=0&&b[i]cout对于堆,底层数据结构中保存的元素顺序并不重要
您应该检查最小堆中弹出的值是否按升序排列,即根元素始终为最小值
将top()
和pop()
方法添加到这两个结构中。top()
将简单地返回根元素值,pop()
将删除根元素并用堆中合适的元素替换它
下面的代码应该以相同的顺序打印元素
while(heap.size() > 0)
{
std::cout<<heap.top()<<" ";
heap.pop();
}
while(heap.size()>0)
{
如果测试用例有预定义的输出,我如何知道使用哪种方法?