카테고리 없음
우선순위 큐 c code
벤치마킹
2019. 6. 29. 12:22
참고 사이트 https://donggod.tistory.com/111
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | #include <stdio.h> #define MAX_SIZE 100 typedef struct priority_queue { int heap[MAX_SIZE]; int size; priority_queue() { size = 0; } void swap(int *a, int *b) { int tmp = *a; *a = *b; *b = tmp; } int push(int value) { if (size + 1 > MAX_SIZE) { return 0; } heap[size] = value; int current = size; int parent = (size - 1) / 2; while (current > 0 && heap[current] > heap[parent]) { swap(&heap[current], &heap[parent]); current = parent; parent = (parent - 1) / 2; } size++; return 1; } int pop() { if (size <= 0) return -1; int ret = heap[0]; size--; heap[0] = heap[size]; int current = 0; int leftChild = current * 2 + 1; int rightChild = current * 2 + 2; int maxNode = current; while (leftChild < size) { if (heap[maxNode] < heap[leftChild]) { maxNode = leftChild; } if (rightChild < size && heap[maxNode] < heap[rightChild]) { maxNode = rightChild; } if (maxNode == current) { break; } else { swap(&heap[current], &heap[maxNode]); current = maxNode; leftChild = current * 2 + 1; rightChild = current * 2 + 2; } } return ret; } int empty() { if (size == 0) { return 1; } else { return 0; } } }priority_queue; int main(int argc, char* argv[]) { int T, N; scanf("%d", &T); for (int test_case = 1; test_case <= T; test_case++) { scanf("%d", &N); priority_queue pq; for (int i = 0; i < N; i++) { int value; scanf("%d", &value); pq.push(value); } printf("#%d\n", test_case); while(!pq.empty()) printf("%d ", pq.pop()); printf("\n"); } return 0; } | cs |