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 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
|
#include "stdlib.h"
#define Element int #define MinDATA -1
struct ; typedef struct *Two_Heap;
struct { int capacity; int size; int *Array; };
Two_Heap InitHeap(int Maxsize); void Destroy(Two_Heap H); void MakeEmpty(Two_Heap H); void Insert(Element X,Two_Heap H); Element DeleteMin(Two_Heap H); Element FindMin(Two_Heap H); int IsEmpty(Two_Heap H); int IsFull(Two_Heap H);
Two_Heap InitHeap(int Maxsize) { Two_Heap H; H=(Two_Heap)malloc(sizeof(struct node)); if(H==NULL) { printf("no space!n"); return 0; } H->Array=(int*)malloc(sizeof(int)*Maxsize+1); if(H->Array==NULL) { printf("no space!n"); return 0; } H->capacity=Maxsize; H->size=0; H->Array[0]=MinDATA; return H; }
void Destroy(Two_Heap H) { while(IsEmpty(H)!=0) { free(H->Array); free(H); } }
void Insert(Element X,Two_Heap H) { int i; if(IsFull(H)==0) { printf("This Two_Heap has been full.n"); } else { for(i=++H->size;H->Array[i/2]>X;i/=2) H->Array[i]=H->Array[i/2]; H->Array[i]=X; } }
Element DeleteMin(Two_Heap H) { int i,child; Element MinElement,LastElement; if(IsEmpty(H)==0) { printf("No space can be delete,it's empty!n"); return H->Array[0]; } MinElement=H->Array[1]; LastElement=H->Array[H->size--]; for(i=1;i*2<=H->size;i=child) { child=i*2; if(child!=H->size && H->Array[child+1]<H->Array[child]) child++; if(LastElement>H->Array[child]) H->Array[i]=H->Array[child]; else break; } H->Array[i]=LastElement; return MinElement; }
Element FindMin(Two_Heap H) { return H->Array[1]; }
Element IsEmpty(Two_Heap H) { if(H->size==0) return 0; else return 1; }
Element IsFull(Two_Heap H) { if(H->size==H->capacity) return 0; else return 1; }
int main() { Two_Heap H; int maxsize; scanf("%d",&maxsize); H=InitHeap(maxsize); int i; int temp; for(i=0;i<maxsize;i++) { scanf("%d",&temp); Insert(temp,H); } int min1,min2; min1=FindMin(H); DeleteMin(H); min2=FindMin(H); printf("%d %dn",min1,min2); Destroy(H); return 0; }
|
近期评论