码迷,mamicode.com
首页 > 其他好文 > 详细

TopCoder SRM624 BuildingHeightEasy 题解

时间:2014-06-22 08:19:38      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:class   blog   code   使用   数据   2014   

本题题意就是求有一组建筑物,问把这些建筑物的M个都统一到同一高度,需要的最小修改高度是多少?

题意隐含的意思就是因为是建筑物,所以不能减少,只能增加了。

本题可以使用暴力搜索,因为数据量少。

但是其实可以小排序,然后再求高度差的。

排序之后从第M个建筑物开始搜索,第M个建筑物与前面M个建筑物组成的建筑物群肯定是当前最小修改高度了。

一个题目要求的类和一个测试程序:

#include <vector>
#include <algorithm>
#include <limits.h>
#include <math.h>
using namespace std;

class BuildingHeightsEasy
{
public:
	int minimum(int M, vector<int> &heights)
	{
		sort(heights.begin(), heights.end());
		int ans = INT_MAX;
		for (int i = M-1; i < (int)heights.size(); i++)
		{
			int tmp = 0;
			for (int j = i-M+1; j < i; j++) //j = M-i-1居然写成这样的错误
			{
				tmp += heights[i] - heights[j];
			}
			ans = min(ans, tmp);
		}
		return ans;
	}
};

void BuildingHeightsEasy_run()
{
	int m, n;	
	scanf("%d %d", &m, &n);
	vector<int> heights(n);
	for (int i = 0; i < n; i++)
	{
		scanf("%d", &heights[i]);
	}
	BuildingHeightsEasy build;
	printf("%d\n", build.minimum(m, heights));
}




TopCoder SRM624 BuildingHeightEasy 题解,布布扣,bubuko.com

TopCoder SRM624 BuildingHeightEasy 题解

标签:class   blog   code   使用   数据   2014   

原文地址:http://blog.csdn.net/kenden23/article/details/32933351

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!