题解:#9075.做作业 审核通过

ylnywys CSP-J2一等 2025-07-18 9:45:49 11

可以手写堆来完成这道题,从大到小排序,然后输出堆顶

#include <bits/stdc++.h>
using namespace std;
const int N=1e6+7;
int w[N],tot=0;
void push(int x){
	w[++tot]=x;
	int p=tot;
	while(p>1&&w[p/2]<w[p]){
		swap(w[p/2],w[p]);
		p/=2;
	}
}
void pop(){
	swap(w[1],w[tot--]);
	for(int i=1,p;i<=tot;i=p){
		p=2*i;
		if(p+1<=tot&&w[p]<w[p+1])p++;
		if(p<=tot&&w[i]<w[p])swap(w[i],w[p]);
		else break;
	}
}
int main() {
	int n,x;cin>>n;
	for(int i=1;i<=n;i++){
		scanf("%d",&x);
		push(x);
	}
	for(int i=1;i<=n;i++){
		printf("%d ",w[1]);
		pop();
	}
	return 0;
}
{{ vote && vote.total.up }}