Assign banana to monkeys

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27500493/article/details/84107043

Problem description:

There are N Monkeys and N bananas are placed in a straight line. Each monkey want to have a banana, if two monkeys want to own the same banana, there will be a fight! A monkey can stay at his position, move one step right from x to x + 1, or move one step left from x to x -1. Any of these moves consumes 1 second. Assign monkeys to banana so that not monkey fight each other and the time when the last monkey gets a banana is minimized.

Input:

The input contain two arrays of int. The first array is the positions of monkeys. The second array is the positions of bananas.

Output:

The output is a int, which is the time(in seconds) it takes when all bananas are assigned to monkeys.

Sample input:

 1 3 6
 2 4 6

Sample output:

1

Sample explanation:

Assign monkey at position 1 to banana at position 2. (1 second)

Assign monkey at position 3 to banana at position 4. (1 second)

Assign monkey at position 6 to banana at position 6. (0 second)

Overall time is max(1, 1, 0) = 1 second.

方法1,通过数组实现:

#include <iostream>
#include<algorithm>
using namespace std;

int mk[10000000], bn[10000000];//mk猴子,bn香蕉
int main()
{ 
	
	
	int count=0;//当前最大距离差绝对值
	int i=0;

	//依次输入猴子位置,回车结束当前行输入
	while(cin >> mk[i])
	{
			i++;
			if (cin.get() == '\n')
				break;
		
	}
	sort(mk,mk+i);

	//依次输入香蕉位置,回车结束当前行输入
	i = 0;
	while (cin >> bn[i])
	{
			 
			i++;
			if (cin.get() == '\n')
				break;
	
	}
	sort(bn,bn+i);


	//依次比较对应下标位置 猴子移动到对应香蕉 需要的绝对差值,最后选最大的为时间差值
	for (int j = 0; j < i; j++)
	{	
		if(abs(mk[j] - bn[j])>count)
		count=abs(mk[j]-bn[j]);
	}

	cout << count;

	return 0;
}

 方法2,通过vector实现:

#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
	vector<int> mk, bn;//猴子,香蕉
					   
	int count=0;//当前最大距离差绝对值
	int i;


	while (cin >> i)
	{
		 
		mk.push_back(i);
		if (cin.get() == '\n')
			break;

	}
	sort(mk.begin(), mk.end());
	while (cin >> i)
	{
		 
		bn.push_back(i);
		if (cin.get() == '\n')
			break;

	}
	sort(bn.begin(), bn.end());


	for (int j = 0; j < int(mk.size()); j++)
	{
		if(abs(mk[j] - bn[j])>count)
		count = abs(mk[j] - bn[j]);
	}
	cout << count;
	return 0;
}

两种方法在UOJ平台的测试结果对比:

第一个是使用vector ,第二个是使用数组

Vector虽然是动态数组,但是本质上和数组没什么区别,频繁的销毁新建,效率很低,所以正确的做法是新建vector的时候初始化一个合适的大小。vector默认创建给一个初始大小,然后通常按1.5倍增长,因此,此测试例中 vector所占内存 比 自己设定的固定长度数组 内存占用大,耗时间长!

猜你喜欢

转载自blog.csdn.net/qq_27500493/article/details/84107043