HZOJ-287:合并果子

#include 
#include 

void merge_sort(int* arr, int l, int r) {
	if (r - l <= 1) return;
	int mid = (l + r) / 2;
	merge_sort(arr, l, mid);
	merge_sort(arr, mid, r);
	int* temp = (int*)malloc(sizeof(int) * (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;
}
int main() {
	int n;
	scanf_s("%d", &n);
	int* arr = (int*)malloc(sizeof(int) * n);
	for (int i = 0; i < n; i++) scanf_s("%d", &arr[i]);
	merge_sort(arr, 0, n); 
	int c = 0;
	for (int i = 0; i < n - 1; i++) {
		arr[i + 1] += arr[i];
		c += arr[i + 1];
		for (int j = i + 1; j < n - 1; j++) {
			if (arr[j] > arr[j + 1]) {
				int t = arr[j];
				arr[j] = arr[j + 1];
				arr[j + 1] = t;
			}
		}
	}
	printf("%d", c);
	return 0;
}

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