HZOJ-244:奶牛围栏

#include 
#include 
#define MAX 500
typedef struct node {
	int x, y;
} Node;

Node arr[MAX + 5];
int tmp[MAX + 5];

void merge(int* arr, int l, int r) {
	if (r - l < 2) return;
	int mid = (r + l) / 2;
	merge(arr, l, mid);
	merge(arr, mid, r);
	int* temp = (Node*)malloc(sizeof(Node) * (r - l));
	int p1 = l, p2 = mid, k = 0;
	while (p1 < mid || p2 < r) {
		if (p2 == r || (p1 < mid && arr[p1] <= arr[p2])) {
			temp[k++] = arr[p1++];
		}
		else temp[k++] = arr[p2++];
	}
	for (int i = l; i < r; i++) arr[i] = temp[i - l];
	free(temp);
	return 0;
}
void merge_x(Node* arr, int l, int r) {
	if (r - l < 2) return;
	int mid = (r + l) / 2;
	merge_x(arr, l, mid);
	merge_x(arr, mid, r);
	Node* temp = (Node*)malloc(sizeof(Node) * (r - l));
	int p1 = l, p2 = mid, k = 0;
	while (p1 < mid || p2 < r) {
		if (p2 == r || (p1 < mid && arr[p1].x <= arr[p2].x)) {
			temp[k++] = arr[p1++];
		}
		else temp[k++] = arr[p2++];
	}
	for (int i = l; i < r; i++) arr[i] = temp[i - l];
	free(temp);
	return 0;
}


int check_y(Node* arr, int j, int i, int c, int l) {
	int cnt = 0;
	for (int k = j; k <= i; k++) {
		tmp[cnt++] = arr[k].y;
	}
	merge(tmp, 0, cnt);
	for (int i = c - 1; i < cnt; i++) {
		if (tmp[i] - tmp[i - c + 1] < l) 
			return 1;
	}
	return 0;
}

int check(Node* arr, int n, int c, int l) {
	merge_x(arr, 0, n);
	int j = 0;
	for (int i = 0; i < n; i++) {
		while (arr[i].x - arr[j].x >= l) j++;
		if (i - j + 1 < c) continue;
		if (check_y(arr, j, i, c, l)) return 1;
	}
	return 0;
}

int solve(Node* arr, int c, int n) {
	int head = 0, tail = 10000, mid = 0;
	while (head < tail) {
		mid = (head + tail) / 2;
		if (check(arr, n, c, mid)) tail = mid;
		else head = mid + 1;
	}
	return head;
}


int main() {
	int C, N;
	scanf("%d%d", &C, &N);
	for (int i = 0; i < N; i++) scanf("%d%d", &arr[i].x, &arr[i].y);
	printf("%d", solve(arr, C, N));
	return 0;
}

你可能感兴趣的:(算法题,算法,数据结构,排序算法)