#include<stdio.h> #include<stdlib.h> #include<string.h> #define leftChild(i) (2*(i)+1) //交换 void swap(int *a, int i, int j) { int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } //堆下溯 void maxHeapify(int *a, int i, int n) { int child, tmp; for (tmp = a[i]; leftChild(i)<n; i = child){ child = leftChild(i); if (child != n - 1 && a[child] < a[child + 1]) ++child; if (tmp < a[child]) a[i] = a[child]; else break; } a[i] = tmp; } //建立最大堆 void buildMaxHeap(int *a, int n) { for (int i = n / 2; i >= 0; --i) maxHeapify(a, i, n); } //堆排序 void heapSort(int *a, int n) { for (int i = n / 2; i >= 0; --i) maxHeapify(a, i, n); for (int i = n - 1; i > 0; --i){ swap(a, 0, i); maxHeapify(a, 0, i); } } typedef struct _stack{ int *arr; int pos; }stack; //创建一个空的优先队列 stack create(int capacity) { stack s; s.pos = -1; s.arr = (int*)malloc(capacity*sizeof(int)); memset(s.arr, 0, capacity*sizeof(int)); return s; } //返回优先队列最大元素 int maxOfStack(stack &s) { return s.arr[0]; } //返回最大元素并删除 int extractMax(stack &s) { swap(s.arr,0,s.pos); --s.pos; return s.arr[s.pos + 1]; } //增大指定元素到key void increaseKey(stack &s, int i, int key) { if (i > s.pos) return; if (key < s.arr[i]) return; s.arr[i] = key; while (i > 0 && s.arr[i] > s.arr[(i - 1) / 2]){ swap(s.arr, i, (i - 1) / 2); i = (i - 1) / 2; } } //插入元素 void insert(stack &s, int val) { ++s.pos; s.arr[s.pos] = val; increaseKey(s, s.pos, val); } //思考题6.2,d叉堆 void increaseKeyD(int *a, int i, int key,int d) { if (a[i] > key) return; a[i] = key; while (i > 0 && a[i] > a[(i - 1) / d]){ swap(a, i, (i - 1) / d); i = (i - 1) / d; } } //思考题6.3,young氏矩阵 void maxHeapYoung(int *a, int i, int j, int m, int n) { int tmp, x, y; while (tmp = a[i*n + j]){ x = i; y = j; if (x < m - 1 && y < n - 1){ if (a[x*n + y + 1] > a[(x + 1)*n + y]) ++x; else ++y; } else if (x < m - 1) ++x; else if (y < n - 1) ++y; else break; if (tmp > a[x*n + y]) a[i*n + j] = a[x*n + y]; else break; i = x; j = y; a[i*n + j] = tmp; } } int main() { int a[] = { 3, 5, 7, 20,-1,-5,9, 8, 6, 4, 1 }; stack s = create(20); for (int i = 0; i < 11; ++i) insert(s, a[i]); for (int i = 0; i <= s.pos; ++i) printf("%d\t", s.arr[i]); printf("\n"); int b[] = { 100, 5, 12, 3, 8, 14, 4, 9, 16 }; maxHeapYoung(b, 0, 0, 3, 3); for (int i = 0; i < 9; ++i) printf("%d\t", b[i]); printf("\n"); }
堆:stack
队列:queue
优先队列:priority_queue
for all
size_type
value_type
container_type
A a;
A a(c);
关系运算 == != < <= > >=
a.empty();
a.size();
swap(a,b);
a.swap(b);
for stack
stack<int>,默认基于deque实现;可以指定为list/vector,stack<int,vector<int>>
s.pop(); 删除
s.push(item); 入栈
s.emplace(args); 入栈
s.top(); 返回
for queue
queue<int>,默认基于deque,可指定list/vector,queue<int,vector<int>>
q.front();
q.back();
q.push(item);
q.emplace(args);
q.pop();
- for priority_queue
- prioriry_queue<int>默认基于vector,less<int>,可指定deque,greater<int>,priority_queue<int,deque<int>,greater<int>>
- pq.top();
- pq.push(item);
- pq.emplace(args);
- pq.pop();
时间: 2024-10-05 07:16:01