Posts

Search

CCT B4 - Assigning mice to Holes

There are N Mice and N holes are placed in a straight line.

Each hole can accomodate only 1 mouse.

A mouse 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 minute.

Assign mice to holes so that the time when the last mouse gets inside a hole is minimized.

Input Format

First line contains the integer N. Next line contains N integers, the position of the mice.
Third line contains N integers, the position of the holes.

Constraints

1 <= N <= 105

Output Format

Output one number corresponding to the minimum number of minutes it will take for the last mice to go into the hole.

Sample Input 0

3
4 -4 2
4 0 5

Sample Output 0

4

Solution :

#include <iostream>
#include <string.h>
#include <stdio.h>

using namespace std;

void sort(int *arr, int left, int right) {
    int p, i, j, temp;
    if (left < right) {
        i = left;
        j = right;
        p = left;
        while (i < j) {
            while (arr[i] <= arr[p] && i < right) {
                i++;
            }
            while (arr[j] > arr[p]) {
                j--;
            }
            if (i < j) {
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        temp = arr[p];
        arr[p] = arr[j];
        arr[j] = temp;
        sort(arr, left, j - 1);
        sort(arr, j + 1, right);
    }
}

int solveCase(int n, int *hole, int *mouse) {
    int time = 0;
    sort(hole, 0, n - 1);
    sort(mouse, 0, n - 1);
    for (int j = 0; j < n; j++) {
        int g = mouse[j] - hole[j];
        if (g < 0) {
            g = -g;
        }
        if (g > time) {
            time = g;
        }
    }
    return time;
}

int main() {
    int _n;
        cin >> _n;
        int _hole[_n], _mouse[_n], _time;
        for(int j = 0; j < _n; j++) {
            cin >> _hole[j];
        }
        for(int j = 0; j < _n; j++) {
            cin >> _mouse[j];
        }
        cout << solveCase(_n, _hole, _mouse) << endl;
    
    return 0;
}