|
楼主 |
发表于 2021-6-8 09:21:27
|
显示全部楼层
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int Heap[50001];//从1开始计数
int size=0; //heap size
void insert(int val) {
int i = ++size;
//please finish the following parts
while (i > 1 && val < Heap[i/2] ){ //finish this bracket
Heap[i] = Heap[i/2];
i = i / 2;
}
Heap[i] = val;
}
int delete_min() {
int val = Heap[size--], ret = Heap[1];
int i = 1, ch = 2;
// please finish the following parts
while ( ch <= size){//finish this bracket
if(ch < size && Heap[ch+1] < Heap[ch] ) ch++;
if(val <= Heap[ch]) break;
Heap[i] = Heap[ch];
i = ch;
ch += ch;
}
Heap[i] = val;
return ret;
}
int n, data1, data2, weight = 0;
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{int temp;
cin>>temp;
insert(temp);}
for (int i = 0; i < n-1; i++) {
data1 = delete_min();
data2 = delete_min();
weight += data1 + data2;
insert(data1 + data2);
}
cout << weight ;
return 0;
} |
|