c++算法优化

C++语言 码拜 8年前 (2016-04-11) 1282次浏览
描述
在一个果园里,多多已经将全部的果子打了下来,而且按果子的不同种类分成了不同的堆。多多决定把全部的果子合成一堆。
每一次合并,多多可以把两堆果子合并到一起,消耗的体力等于两堆果子的重量之和。可以看出,全部的果子经过n-1次合并之后,就只剩下一堆了。多多在合并果子时总共消耗的体力等于每次合并所耗体力之和。
原因是还要花大力气把这些果子搬回家,所以多多在合并果子时要尽可能地节省体力。假定每个果子重量都为1,并且已知果子的种类数和每种果子的数目,你的任务是设计出合并的次序方案,使多多耗费的体力最少,并输出这个最小的体力耗费值。
例如有3种果子,数目依次为1,2,9。可以先将1、2堆合并,新堆数目为3,耗费体力为3。接着,将新堆与原先的第三堆合并,又得到新的堆,数目为12,耗费体力为12。所以多多总共耗费体力=3+12=15。可以证明15为最小的体力耗费值。
用堆写了一个,但是测试通不过,本人优化过后也不行,老是超时,不知道该怎么有优化了

#include <iostream>
#include <stdio.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int *arr;
int energy=0;
int total;
int n;
int order=0;//第几个堆 
int bubble(int *a,int k)
{
	for(int i=0;i<k;++i)
	{
		for(int j=k-1;j>i;j--)
		{
			if(a[i]>a[j])
			{
				swap(a[i],a[j]);
			}
		}
	}
}
int find()
{
	energy+=arr[order]+arr[order+1];
	arr[order+1]=arr[order]+arr[order+1];
	++order; 
	--n;
	return 0;
}
int main(int argc, char** argv)
 {
 
	scanf("%d",&total);
	n=total;//堆数 
	arr=new int[total];
	for(int i=0;i<total;++i)
	{
		scanf("%d",&arr[i]);
	} 
	while(n!=1)
	{
		bubble(arr,total) ;
		find();
	}
	 printf("%d",energy);
	 delete []arr;
	return 0;
}
解决方案

20

排序qsort之类的,然后以二叉排序树的性质递归那个数组

20

这是一道题吧,算法就是7楼所说,用STL很容易就写出来了

#include <iostream>
#include <algorithm>
#include <list>
using namespace std;
int main()
{
	list<int> fruits({9,3,100,5,6,1,2});
	fruits.sort();
	int remain=fruits.size();
	int strength=0;
	while (remain>1)
	{
		if (remain==2)
		{
			strength+=fruits.front()+fruits.back();
			break;
		}
		else
		{
			auto it=fruits.begin();
			int tmp=*it++;
			tmp+=*it;
			strength+=tmp;
			fruits.insert(lower_bound(fruits.begin(),fruits.end(),tmp),tmp);
			fruits.pop_front();
			fruits.pop_front();
			remain--;
		}
	}
	cout<<strength<<endl;
	return 0;
}

不用STL的话就是单链表操作了,链表排序和插入,写几个函数也不难


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c++算法优化
喜欢 (0)
[1034331897@qq.com]
分享 (0)