HZOJ-245:货仓选址

#include 
#include 

void merge_sort(int* arr, int l, int n) {
	if (n - l <= 1) return;
	int mid = (l + n) / 2;
	merge_sort(arr, l, mid);
	merge_sort(arr, mid, n);
	int* temp = (int*)malloc(sizeof(int) * (n - l));
	int p1 = l, p2 = mid, k = 0;
	while (p1 < mid || p2 < n) {
		if (p2 == n || (p1 < mid && arr[p1] <= arr[p2])) {
			temp[k++] = arr[p1++];
		}
		else temp[k++] = arr[p2++];
	}
	for (int i = l; i < n; i++) arr[i] = temp[i - l];
	free(temp);
	return;
}
int main() {
	int n;
	scanf("%d", &n);
	int* arr = (int*)malloc(sizeof(int) * n);
	for (int i = 0; i < n; i++) scanf("%d ", &arr[i]);
	merge_sort(arr, 0, n);
	int ans = 0;
	for (int i = 0; i < n; i++) ans += abs(arr[n / 2] - arr[i]);
	printf("%d", ans);
	return 0;
}

你可能感兴趣的:(算法题,算法)