void swap(int *array, int a, int b)
{
int tmp = array[a];
array[a] = array[b];
array[b] = tmp;
}
void heapfy(int *array, int n, int i)
{
if(i >= n) {
return ;
}
int c1 = i * 2 + 1;
int c2 = i * 2 + 2;
int max = i;
// printf("%d\n",n);
// printf("max=%d,i=%d,c1=%d,c2=%d\n",max,i,c1,c2);
// printf("%d\n",n);
if(c1 < n && array[c1] > array[max]) {
// printf("%d,%d\n",array[c1],array[max]);
max = c1;
}
if(c2 < n && array[c2] > array[max]) {
// printf("%d,%d\n",array[c2],array[max]);
max = c2;
}
//printf("%d,%d,%d\n",array[c1],array[c2],array[max]);
// printf("max=%d,i=%d\n",max,i);
if(max != i) {
swap(array, max, i);
heapfy(array, n, max);
}
}
void build_heapy(int *array, int n)
{
int last = n-1;
for(int i = (last-1)/2; i>=0; i--) {
heapfy(array, n, i);
}
}
void sort_heap(int *array, int n)
{
build_heapy(array, n);
// for(int i = n-1; i >=0; i--) {
// swap(array, i, 0);
// heapfy(array, i, 0);
// }
}
int heap_pop(int *array, int n)
{
int tmp = array[0];
swap(array, n-1, 0);
heapfy(array,n-1, 0);
return tmp;
}
void heap_push(int *array, int n, int value)
{
array[n-1] = value;
build_heapy(array, n);
}
int lastStoneWeight(int* stones, int stonesSize){
build_heapy(stones, stonesSize);
int totolnum = stonesSize;
if(stonesSize == 1) {
return stones[0];
}
for(int i = 0; i < totolnum; i++) {
printf("%d\n",stones[i]);
}
while(1) {
int first = heap_pop(stones, totolnum);
totolnum--;
int second = heap_pop(stones,totolnum);
totolnum--;
printf("(%d,%d, totolnum=%d)",first, second, totolnum);
if(first != second) {
int value = first-second;
totolnum++;
heap_push(stones, totolnum, value);
}
if(totolnum == 0) {
return 0;
}
if(totolnum == 1) {
return stones[0];
}
}
return 0;
}
1046. 最后一块石头的重量
最新推荐文章于 2024-11-01 14:48:20 发布