刚开始用暴力方法写的,没过。然后改的小根堆。
自己用写的小根堆,没用STL。然后就是哈夫曼树。
1 /* 2 任务重了,要用小根堆来写。+哈夫曼树 3 */ 4 #include <stdio.h> 5 #include <algorithm> 6 #define maxn 20000+10 7 #define L sign*2 8 #define R sign*2+1 9 using namespace std; 10 int heap[maxn]; 11 int heapSize; 12 long long cnt; 13 bool cmp(int a,int b) 14 { 15 return a<b; 16 } 17 int find_min_1() //第一次找到最小值并且维护最小堆 1,2,3....heapSize 18 { 19 int t; 20 int res; 21 t=heap[1];heap[1]=heap[heapSize];heap[heapSize]=t; 22 res=t; 23 heapSize--; 24 bool SIGN; 25 int sign=1; 26 while(1) 27 { 28 if(L<=heapSize&&R<=heapSize&&heap[sign]>heap[L]&&heap[sign]>heap[R]) 29 { 30 if(heap[L]<heap[R]) 31 { 32 SIGN=0; 33 } 34 else 35 SIGN=1; 36 } 37 else if(L<=heapSize&&heap[sign]>heap[L]) 38 { 39 SIGN=0; 40 } 41 else if(R<=heapSize&&heap[sign]>heap[R]) 42 { 43 SIGN=1; 44 } 45 else break; 46 47 if(SIGN==0) 48 { 49 t=heap[sign]; 50 heap[sign]=heap[L]; 51 heap[L]=t; 52 sign=L; 53 } 54 else if(SIGN==1) 55 { 56 t=heap[sign]; 57 heap[sign]=heap[R]; 58 heap[R]=t; 59 sign=R; 60 } 61 } 62 return res; 63 } 64 int find_min_2() //第二次找到最小值,不用维护 65 { 66 return heap[1]; 67 } 68 void push(int n) //插入一个元素到堆里里面并维护最小堆 69 { 70 heap[1]=n; 71 cnt+=n; 72 int t; 73 int sign=1; 74 bool SIGN; //SIGN=0 代表找左子树 SIGN=1 代表找右子树 75 while(1) 76 { 77 78 if(L<=heapSize&&R<=heapSize&&heap[sign]>heap[L]&&heap[sign]>heap[R]) 79 { 80 if(heap[L]<heap[R]) 81 { 82 SIGN=0; 83 } 84 else 85 SIGN=1; 86 } 87 else if(L<=heapSize&&heap[sign]>heap[L]) 88 { 89 SIGN=0; 90 } 91 else if(R<=heapSize&&heap[sign]>heap[R]) 92 { 93 SIGN=1; 94 } 95 else break; 96 97 if(SIGN==0) 98 { 99 t=heap[sign]; 100 heap[sign]=heap[L]; 101 heap[L]=t; 102 sign=L; 103 } 104 else if(SIGN==1) 105 { 106 t=heap[sign]; 107 heap[sign]=heap[R]; 108 heap[R]=t; 109 sign=R; 110 } 111 112 } 113 } 114 int main() 115 { 116 int i,t; 117 while(~scanf("%d",&heapSize)) 118 { 119 cnt=0; 120 for(i=1;i<=heapSize;++i) 121 { 122 scanf("%d",&heap[i]); 123 } 124 heap[0]=-1; 125 sort(heap,heap+heapSize+1,cmp); 126 while(heapSize!=1) 127 { 128 t=find_min_1()+find_min_2(); 129 push(t); 130 } 131 printf("%lld\n",cnt); 132 } 133 return 0; 134 }