Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <string>
- #include <algorithm>
- using namespace std;
- #define MAXN 99
- #define L(n) (2*n)
- #define R(n) (2*n+1)
- #define P(n) (int)(n/2)
- struct Node {
- int p;
- string s;
- void swap(Node &other) {
- Node tmp = (Node){p, s};
- p = other.p, s = other.s;
- other.p = tmp.p, other.s = tmp.s;
- }
- };
- class Queue {
- public:
- Node pq[MAXN];
- int size;
- void bubble_up(int u);
- void bubble_down(int u);
- void add(string s, int p);
- string remove();
- private:
- int a = 1;
- int b = 1;
- };
- void Queue::bubble_up(int u) {
- while(P(u)) {
- if(pq[P(u)].p > pq[u].p) {
- pq[u].swap(pq[P(u)]);
- u = P(u);
- } else break;
- }
- }
- void Queue::bubble_down(int u) {
- while(L(u) <= size) {
- int pp = min(pq[u].p, pq[L(u)].p);
- if(R(u) <= size) pp = min(pp, pq[R(u)].p);
- if(pp == pq[u].p) break;
- else if(pp == pq[L(u)].p) {
- pq[u].swap(pq[L(u)]);
- u = L(u);
- } else {
- pq[u].swap(pq[R(u)]);
- u = R(u);
- }
- }
- }
- void Queue::add(string s, int p) {
- pq[++size] = (Node){p, s};
- bubble_up(size);
- }
- string Queue::remove() {
- string ret = pq[1].s;
- pq[1].swap(pq[size--]);
- bubble_down(1);
- return ret;
- }
- int main() {
- Queue q;
- q.add("X", 10);
- q.add("Y", 1);
- q.add("Z", 3);
- cout << q.remove() << endl;
- cout << q.remove() << endl;
- cout << q.remove() << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement