foj 1327 Blocks of Stones II

Problem Description

There are n blocks of stones in a line laying on the ground. Now you are to merge these blocks of stones together with the restriction that you can only merge the neighbouring blocks each time. The score you get for each merging is the number of stones the new blocks has.
Before each merging, you are allowed to swap any neighbouring blocks for any times. You are to calculate the minimal score you will get during the whole process.

Input

There are multiple test cases. For each case, the first line contains a integer n(n<=10000), representing the number of blocks. The second line contains n integers, representing number of stones in each blocks.

Output

For each case, output one line containing a single integer, representing the minimal score. The results are within 32bit integers.

Sample Input

3
2 5 1

Sample Output

11

一开始题目都没看懂,后来理解一下大概是以下描述:

一开始 2 5 1 然后将1 2合并得到分数3
合并后得到 3 5 然后将 3 5合并得到分数 8
所以分数为3 + 8=11

题意就是求其最少分数,每次合并分数的总和最少

可以说是有关贪心的算法

以下为代码

#include<iostream>
#include<algorithm>
using namespace std;
int a[10001];
int s[10001];
int main()
{
	int n,i,j,sum=0,temp,k;
	while(cin>>n)
	{
		j=0;
		for(i=0;i<n;i++)
		{
			cin>> a[i];
		}	
		sort(a,a+n);
		for(i=0;i<n-1;i++){
			
			s[j]=a[i]+a[i+1];
			a[i+1]=s[j];
			for(k=i+1;k<n-1;k++){
				if(a[k]>a[k+1]){
					temp=a[k];
					a[k]=a[k+1];
					a[k+1]=temp;	
				}
				else break;
			}
			sum+=s[i];
			j++;	
		}
		cout<<sum<<endl;
		sum=0;	 	
	}
	return 0;
} 

posted on 2017-04-04 21:09  linese-d  阅读(216)  评论(0)    收藏  举报

导航