当前位置: 代码迷 >> 综合 >> priority_queue 理解应用
  详细解决方案

priority_queue 理解应用

热度:37   发布时间:2024-02-01 05:25:22.0
/* priority_queue 理解应用 https://blog.csdn.net/lyw_321/article/details/78069794 */
#include <iostream>
#include <queue>
#include <cstdio>
#include <string>
using namespace std;
struct node
{int weight;char s[11];// 重载运算符 ,升序bool operator<(const node &Node) const{return weight > Node.weight;}
};
priority_queue<node> q;
int main()
{string op;node Node;int n;int number;cin >> n;for (int i = 0; i < n; i++){cin >> op; // 输入if (op[0] == 'P'){scanf("%s %d", Node.s, &Node.weight);q.push(Node);// scanf printf 会比 cout cin 快一点}else{if (q.empty()){printf("EMPTY QUEUE\n");}else{printf("%s\n", q.top().s);q.pop();}}}
}

这个是使用了stl, 也可以自己定义,当然也是使用最小堆

#include <iostream>
#include <queue>
#include <cstdio>
#include <string.h>
#include <stdlib.h>
using namespace std;typedef struct heap
{int weight;char s[11];
} Heap;struct heapstruct
{int size;Heap *myheap;
};
typedef struct heapstruct *Minheap;
//最小堆
Minheap new_heap(Minheap p, int n)
{p = new struct heapstruct;p->myheap = new Heap[n + 1];p->size = 0;p->myheap[0].weight = -1;// 设置为比所有的都要小 ,防止i==0 在节点中return p;
}
Minheap in_heap(Minheap p, int n, Heap h)
{int i;if (p = NULL){p = new_heap(p, n);}// 这就体现出 myheap[0].weight 设置为 -1的意义了for (i = ++p->size; p->myheap[i / 2].weight > h.weight; i = i / 2){strcpy(p->myheap[i].s, p->myheap[i / 2].s);p->myheap[i].weight = p->myheap[i / 2].weight;}p->myheap[i].weight = h.weight;strcpy(p->myheap[i].s, h.s);return p;// 其实不用返回指针的 // 这个与之前写过的堆排序是不同的 ,这个可以说是在动态的建立
}
Heap delete_node(Minheap p)
{// 返回一个指针// 这个与之前写过的堆排序有点类似了Heap h, temp;int child,i;h.weight = p->myheap[1].weight;strcpy(h.s, p->myheap[1].s);temp.weight = p->myheap[1].weight;strcpy(temp.s, p->myheap[1].s);p->myheap[1].weight = p->myheap[p->size].weight;strcpy(p->myheap[1].s, p->myheap[p->size--].s);for ( i = 1; i <= p->size / 2; i = child){child = i * 2;if (child+1<=p->size && p->myheap[child].weight>p->myheap[child+1].weight){child++;}if(temp.weight<p->myheap[child].weight){//return h;}else{p->myheap[i].weight=p->myheap[child].weight;strcpy(p->myheap[i].s,p->myheap[child].s);}}p->myheap[i].weight=temp.weight;strcpy(p->myheap[i].s,temp.s);return h;
}int main()
{int n;string op;string str;Heap h;Minheap minheap = NULL;cin >> n;for (int i = 0; i < n; i++){cin >> op;if (op[0] == 'P'){// 输入的话cin>>h.s>>h.weight;minheap=in_heap(minheap,n,h);}else{if(!minheap->size){}else {h=delete_node(minheap);}}}
}

参考文档:

https://blog.csdn.net/lyw_321/article/details/78069794
https://blog.csdn.net/op_mocun/java/article/details/104849096