求助0分手写堆
查看原帖
求助0分手写堆
765280
Huyh12楼主2023/1/10 11:38
#include<bits/stdc++.h>
using namespace std;
int heap[10001],n,size=0;
void shiftup(int p) {
	while(p>1&&heap[p]<heap[p/2]) {
		swap(heap[p],heap[p/2]);
		p/=2;
	}
}
void insert(int x) {
	heap[size++]=x;
	shiftup(size);
}
void down(int q) {
	int s=q*2;
	while(s<=size)
  	{
    	if(s<size&&heap[s+1]<heap[s]) 
			s++; 
    	if(heap[s]<heap[q])
    	{
      		swap(heap[s],heap[q]);
      		q=s; 
			s=q*2;
    	}
    	else 
			break;
  }
}
void extract() {
	heap[1]=heap[size--];
	down(1);
}
int main() {
	cin>>n;
	for(int i=1;i<=n;i++) {
		int a;
		cin>>a;
		insert(a);
	}
	long long ans=0;
	while(size>=2) {
		int top1=heap[1];
		extract();
		int top2=heap[1];
		extract();
		ans+=(top1+top2);
		insert(top1+top2);
	}
	cout<<ans<<endl;
	return 0;
}
2023/1/10 11:38
加载中...