【贪心算法】Assign banana to monkeys

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.

原题地址

UOJ#32

代码如下:注意输入如果很多时,将cin改为scanf能很大程度上降低耗时。

#include <iostream>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
/**
 * Assign banana to monkeys 
 */
class Solution {
public:
    int minTime(vector<int>& posMon, vector<int>& posBan){
        N = posMon.size();
        for(int i = 0;i < N;i++){
            if(minimTime < abs(posBan[i] - posMon[i]))
                minimTime = abs(posBan[i] - posMon[i]);
        }
        return minimTime;
    }
private:
    int N, minimTime = 0;
};
int main(){
    int element;
    vector<int> posMon, posBan;  // M个猴子和N个香蕉
    while (cin.peek()!='\n'){
        scanf("%d", &element);
        posMon.push_back(element);
    }
    cin.get();      // 将缓冲区的'\n'取出,防止进入下一个循环
    while (cin.peek()!='\n'){
        scanf("%d", &element);
        posBan.push_back(element);
    }
    sort(posMon.begin(), posMon.end());
    sort(posBan.begin(), posBan.end());
    Solution sol;
    cout<<sol.minTime(posMon, posBan)<<endl;
    return 0;
}

在这里插入图片描述

发布了126 篇原创文章 · 获赞 438 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/SL_World/article/details/103319892