#include<iostream>
#include<assert.h>
#include<stdlib.h>
#define DefaultSize 1000
using namespace std;
struct car {
string add;
int num;
int n;
} a[100];
template<class E>
class MinHeap {
public:
MinHeap(int sz = 100); //构造函数
MinHeap(E arr[],int n); //构造函数:通过一个数组建堆
~MinHeap() { //析构函数
delete []heap;
}
bool Insert(const E &x); //将x插入到最小堆中
E RemoveMin(); //删除堆顶上的最小元素
E IsEmpty()const { //判断空否?空返回1,否则0
return (currentSize == 0) ? true : false;
}
bool IsFull()const { //判断满否?满返回1,否则0
return (currentSize == maxHeapSize) ? true : false;
}
void MakeEmpty() { // 置空堆
currentSize = 0;
}
void output();
private:
car *heap; //存放最小堆中元素的数组
int currentSize; //最小堆中当前元素个数
int maxHeapSize; //最小堆最多允许元素个数
void siftDown(int start,int m); //从Start到m下滑调整成为最小堆
void siftUp(int start); // 从Start到0上滑调整成为最小堆
};
//创建最小堆的两个构造函数
template<class E>
MinHeap<E>::MinHeap(int sz) {
maxHeapSize = (DefaultSize < sz) ?sz: DefaultSize;
heap = new car[maxHeapSize];
if(heap == NULL) {
cerr<<"堆存储分配失败!"<<endl;
exit(1);
}
currentSize = 0;
};
template<class E>
MinHeap<E>::MinHeap(E arr[],int n) {
maxHeapSize = (DefaultSize<n)? n: DefaultSize;
heap = new car[maxHeapSize];
if(heap == NULL) {
cerr<<"堆存储分配失败!"<<endl;
exit(1);
}
for(int i = 0; i<n; i++) heap[i] = arr[i];
currentSize = n;
int currentPos = (currentSize-2)/2;
while(currentPos >= 0) {
siftDown(currentPos,currentSize-1);
currentPos--;
}
};
//最小堆的下滑调整算法
template<class E>
void MinHeap<E>::siftDown(int start, int m) {
int i = start,j = 2*i+1;
E temp = heap[i].num;
while(j<=m) {
if(j<m&&heap[j].num>heap[j+1].num) j++;
if(temp<=heap[j].num)break;
else {
heap[i].num = heap[j].num;
i=j;
j=2*j+1;
}
}
heap[i].num = temp;
};
//最小堆的上滑调整操作
template<class E>
void MinHeap<E>::siftUp(int start) {
int j=start,i=(j-1)/2;
E temp = heap[j].num;
while(j>0) {
if(heap[i].num<=temp) break;
else {
heap[j].num = heap[i].num;
j=i;
i = (i-1)/2;
}
}
heap[j].num=temp;
};
//最小堆的插入算法
template<class E>
bool MinHeap<E>::Insert(const E &x) {
heap[currentSize].num=x;
siftUp(currentSize);
currentSize++;
return true;
};
//最小堆的删除算法
template<class E>
E MinHeap<E>::RemoveMin(){
if(!currentSize){cerr<<"Heap Full"<<endl;return false;}
E x=heap[0].num;heap[0].num=heap[currentSize-1].num;
currentSize--;
siftDown(0,currentSize-1);
return x;
};
int main() {
struct car a[100];
int sum=0,x=0;
int b[100];
int i=0;
MinHeap<int> test(100);
cout<<"请输入当前各个路口信息:"<<endl;
while(cin>>a[i].add>>a[i].num)
{
a[i].n=1;
i++;
sum++;
}
//cmp(a,sum);
for(i=0;i<sum;i++){
test.Insert(a[i].num);
}
for(i=0;i<sum;i++){
b[i]=test.RemoveMin();
}
cout<<"以下是最拥挤的十个路口:"<<endl;
for(i=sum-1;i>=sum-10;i--)
for(int j=sum-1;j>=0;j--)
{
if(x<=10){
if(a[j].num==b[i]&&a[j].n==1)
{
a[j].n=0;
cout<<a[j].add<<endl;
x++;
}
}
}
return 0;
}
堆的代码实现
最新推荐文章于 2023-08-24 15:13:32 发布