关于我的小根堆排序开氧气后MLE变TLE这件事
  • 板块灌水区
  • 楼主湫泷
  • 当前回复8
  • 已保存回复8
  • 发布时间2021/12/16 20:30
  • 上次更新2023/11/3 21:55:41
查看原帖
关于我的小根堆排序开氧气后MLE变TLE这件事
82165
湫泷楼主2021/12/16 20:30

能帮忙看一下代码吗?谢谢!

//小根堆 
#include<bits/stdc++.h>
using namespace std;
const int MAX=1e9+5;
int n,a[100010],ans[100010],cnt,tmp;
int getfirstnotson(int length){
	return length/2;
}
int getsonleft(int now){
	return now*2;
}
int getsonright(int now){
	return now*2+1;
}
int getfather(int now){
	return now/2;
}
void extract(){
	if(cnt==tmp){
		return;
	}
	ans[++cnt]=a[1];
	a[1]=a[n];
	n--;
}
void heapsort(int now){
	if(now==0){
		extract();
		if(n>0){
			heapsort(getfirstnotson(n));
		}
		return;
	}
	int father=a[now],sonleft,sonright;
	int hasright=0,hasleft=0;
	if(getsonleft(now)<=n){
		sonleft=a[getsonleft(now)];	
		hasleft=1;
	}
	if(getsonright(now)<=n){
		sonright=a[getsonright(now)];	
		hasright=1;
	}
	if(hasright==0&&hasleft==0){
		return;
	}
	if(father>sonright&&father>sonleft&&hasleft==1&&hasright==1){
		if(sonright<=sonleft){
			a[getsonright(now)]=father;
			a[now]=sonright;			
			heapsort(getsonright(now));
		}
		else{
			a[getsonleft(now)]=father;
			a[now]=sonleft;
			heapsort(getsonleft(now));
		}
	}
	else if(father>sonright&&hasright==1){
		a[getsonright(now)]=father;
		a[now]=sonright;			
		heapsort(getsonright(now));
	}
	else if(father>sonleft&&hasleft==1){
		a[getsonleft(now)]=father;
		a[now]=sonleft;
		heapsort(getsonleft(now));
	}
	heapsort(now-1);
	return;
}
int main(){
	cin>>n;
	tmp=n;
	memset(a,MAX,sizeof(a));
	for(int i=1;i<=n;i++){
		cin>>a[i];
	}
	heapsort(getfirstnotson(n));
//	printf("cnt=%d\n",cnt);
	for(int i=1;i<=cnt;i++){
		cout<<ans[i]<<" ";
	}
	return 0;
}
/*
建堆(二叉树)
从第一个非叶子节点开始
将最小的元素放在父节点的位置
有交换的话看被交换的子节点往下继续做前一个步骤
再到第二个非叶子节点重复上述步骤(减一) 

提取
将堆顶元素提取出来
最后一个元素放到堆顶
重复建堆

直到最后堆中没有元素 
*/ 
2021/12/16 20:30
加载中...