【合并果子】的两种方法

哈夫曼树+堆

#include
#include
const int maxn=10000+10;
using namespace std;
int a[maxn];
int main(){
	int i,j,k,m,n,ans=0;
	cin>>n;
	for(i=1;i<=n;i++){
		scanf("%d",&a[i]);
		k=i;
		while(k>1 && a[k]1){
		int sum=a[1];
		a[1]=a[len--];
		k=1;
		while((k*2<=len && a[k]>a[k*2])||(k*2+1<=len && a[k]>a[k*2+1])){
			m=k*2;
			if(m+1<=len && a[m]>a[m+1])m++;
			int t=a[k];a[k]=a[m];a[m]=t;
			k=m;
		}
		sum+=a[1];
		a[1]=a[len--];
		k=1;
		while((k*2<=len && a[k]>a[k*2])||(k*2+1<=len && a[k]>a[k*2+1])){
			m=k*2;
			if(m+1<=len && a[m]>a[m+1])m++;
			int t=a[k];a[k]=a[m];a[m]=t;
			k=m;
		}
		ans+=sum;
		a[++len]=sum;
		k=len;
		while(k>1 && a[k]
哈夫曼树+双队列法

#include
#include
#include
const int maxn=100000+10;
using namespace std;
int a[maxn],b[maxn];
bool cmp(int x,int y){
	return x>n;
	for(i=1;i<=n;i++)scanf("%d",&a[i]);
	sort(a+1,a+n+1,cmp);
	for(i=1;i<=n;i++)b[i]=100000000;		
	b[1]=a[1]+a[2];
	ans=b[1];
	int len=1;
	int u=1,v=3;
	while(1){
		int sum=0;
		if(u>len){sum+=a[v];v++;}
		else if(v>n){sum+=b[u];u++;}
		else if(v<=n && a[v]=b[u]){sum+=b[u];u++;}
		
		if(u>len){sum+=a[v];v++;}
		else if(v>n){sum+=b[u];u++;}
		else if(v<=n && a[v]=b[u]){sum+=b[u];u++;}
		
		ans+=sum;
		b[++len]=sum;
		if(n-v+1+len-u+1<=1)break;
	}
	cout<



你可能感兴趣的:(程序代码,算法分享)