【NOIP 2004 提高组】合并果子

题就自己找啦,各大OJ上应该都有

【题目】

题目描述:

在一个果园里,多多已经将所有的果子打了下来,而且按果子的不同种类分成了不同的堆。多多决定把所有的果子合成一堆。

每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和。可以看出,所有的果子经过n-1次合并之后,就只剩下一堆了。多多在合并果子时总共消耗的体力等于每次合并所耗体力之和。

因为还要花大力气把这些果子搬回家,所以多多在合并果子时要尽可能地节省体力。假定已知每个果子重量都为1,并且已知果子的种类数和每种果子的数目,你的任务是设计出合并的次序方案,使多多耗费的体力最少,并输出这个最小的体力耗费值。

例如有三种果子,数目依次为1,2,9。可以先将 1、2堆合并,新堆数目为3,耗费体力为3。接着,将新堆与原先的第三堆合并,又得到新的堆,数目为12,耗费体力为12。所以多多总共耗费体力为3+12=15。可以证明15为最小的体力耗费值。

输入格式:

输入文件包括两行,第一行是一个整数 n (1 ≤ n ≤ 10000),表示果子的种类数。第二行包含 n 个整数,用空格分隔,第 i 个整数ai(1 ≤ ai ≤ 20000)是第 i 种果子的数目。

输出格式:

输出文件包括一行,这一行只包含一个整数,也就是最小的体力耗费值。输入数据保证这个值小于2^{31}

样例数据:

输入
3
1 2 9

输出
15

备注:

【数据规模】
对于 30% 的数据,保证有 n ≤ 1000;
对于 50% 的数据,保证有 n ≤ 5000;
对于全部的数据,保证有 n ≤ 10000。

【分析】

相信大家学堆的时候都做过这道题吧

没做过也没办法

贪心策略就是每次都取出最小的两堆果子来合并,直到最后只剩一堆

而最小的两堆果子我们就用来维护

时间复杂度是O(n * log n)

【代码】

用STL中优先队列的代码:

#include<queue>
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 10005
using namespace std;
priority_queue<int>q;
int main()
{
	int n,i,x,t,ans=0;
	scanf("%d",&n);
	for(i=1;i<=n;++i)
	{
		scanf("%d",&x);
		q.push(-x);
	}
	while(--n)
	{
		t=0;
		t-=q.top();q.pop();
		t-=q.top();q.pop();
		ans+=t;
		q.push(-t);
	}
	printf("%d",ans);
	return 0;
}

手写堆的代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 10005
using namespace std;
int sum,a[N];
void pushup(int i)
{
	while(i/2>=1)
	{
		if(a[i]<a[i/2])
		{
			swap(a[i],a[i/2]);
			i/=2;
		}
		else  break;
	}
}
void pushdown(int i)
{
	int x;
	while(i*2<=sum)
	{
		x=i*2;
		if(x+1<=sum&&a[x+1]<a[x])
		  x++;
		if(a[i]>a[x])
		{
			swap(a[i],a[x]);
			i=x;
		}
		else  break;
	}
}
void push(int x)
{
	sum++;
	a[sum]=x;
	pushup(sum);
}
void pop()
{
	swap(a[1],a[sum]);
	sum--;
	pushdown(1);
}
int main()
{
	int n,i,x,t,ans=0;
	scanf("%d",&n);
	for(i=1;i<=n;++i)
	{
		scanf("%d",&x);
		push(x);
	}
	while(--n)
	{
		t=0;
		t+=a[1];pop();
		t+=a[1];pop();
		ans+=t;
		push(t);
	}
	printf("%d",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/forever_dreams/article/details/81481504