跳到正文

题解

P6033 合并果子加强版题解

Queue_Priority约 3 分钟
原文
文章信息与版本

文章信息

收录
2026年2月14日
更新
2026年2月16日
篇幅
约 3 分钟
题目
P6033

版本

  1. v2当前
  2. v1

题目传送门

做这题前,我们通常会先做 P1090——这题的弱化版。用优先队列(小根堆)维护,每次合并最小两个即可。

C++
#include <iostream>
#include <queue>
using namespace std;
priority_queue<int,vector<int>,greater<int> > q;
int n,ans;
int main()
{
	cin >> n;
	for (int i=1;i<=n;i++)
	{
		int a;
		cin >> a;
		q.push(a);
	}
	for (int i=1;i<n;i++)
	{
		int x=q.top();q.pop();
		int y=q.top();q.pop();
		int sum=x+y;
		ans+=sum;
	    q.push(sum);
	}
	cout << ans;
	return 0;
}

这两题唯一不同的是数据范围,上一题复杂度nlogn还没开long long显然会超时。思考优化的方法。

首先可以用桶排序。使用一个队列q1从小到大入队即可。

再用一个队列q2储存合并的结果(显然先入队的更小),每次取的时候比较两个队队头,取最小值。注意数据太【数据删除】,卡常,要快读。

具体见代码。

C++
#include <iostream>
#include <queue>
#include <string>
using namespace std;
long long n,a[100005],ans;
queue<long long> q1,q2;
long long read()
{
	long long f=1,k=0;
	char c=getchar();
	while(c<'0'||c>'9')
	{
		if(c=='-')f=-1;
		c=getchar();
	}
	while(c>='0'&&c<='9')
	{
		k=k*10+c-'0';c=getchar();
	}
	return k*f;
}
int main()
{
	n=read();
	for (int i=1;i<=n;i++)
	{
		long long x;
		x=read();
		a[x]++;
	}
	for (int i=1;i<=100000;i++)
	{
		if(a[i])
		{
			for (int j=1;j<=a[i];j++)
			{
				q1.push(i);
			}
		}
	}
	for (int i=1;i<n;i++)
	{
		long long x,y;
		if(q2.empty()||q1.front()<q2.front()&&q1.size())
		{
			x=q1.front();q1.pop();
		}
		else
		{
			x=q2.front();q2.pop();
		}
		if(q2.empty()||q1.front()<q2.front()&&q1.size())
		{
			y=q1.front();q1.pop();
		}
		else
		{
			y=q2.front();q2.pop();
		}
		ans+=x+y;
		q2.push(x+y);
	}
	printf("%lld",ans);
	return 0;
}
原文