1 int heap[SIZE], n; 2 void up(int p) 3 { 4 while (p > 1) 5 { 6 if (heap[p] > heap[p/2]) 7 { 8 swap(heap[p], heap[p/2]); 9 p/=2; 10 } 11 else break; 12 } 13 } 14 void down(int p) 15 { 16 int s = p*2; 17 while (s <= n) 18 { 19 if (s < n && heap[s] < heap[s+1]) s++; 20 if (heap[s] > heap[p]) 21 { 22 swap(heap[s], heap[p]); 23 p = s, s = p*2; 24 } 25 else break; 26 } 27 } 28 void insert(int val) 29 { 30 heap[++n] = val; 31 up(n); 32 } 33 void extract() 34 { 35 heap[1] = heap[n--]; 36 down(1); 37 } 38 void remove(int k) 39 { 40 heap[k] = heap[n--]; 41 up(k), down(k); 42 }
huffman树
P1090 合并果子 https://www.luogu.org/problemnew/show/P1090
1 sort(a+1,a+n+1); 2 b[1]=a[1]+a[2];ans=b[1]; 3 FOR(k,1,n-2) 4 { 5 if(a[i]>b[j]&&j<=c) {k1=b[j];j++;} 6 else 7 { 8 if(i<=n) {k1=a[i];i++;} 9 else {k1=b[j];j++;} 10 } 11 if(a[i]>b[j]&&j<=c) {k2=b[j];j++;} 12 else 13 { 14 if(i<=n) {k2=a[i];i++;} 15 else {k2=b[j];j++;} 16 } 17 b[++c]=k1+k2;ans+=b[c]; 18 } 19 cout<<ans;
对于k>2叉树,加一些权值为0的点,使叶子树满足(n-1)%(k-1)==0