HZOJ-284:超市卖货

#include 
#include 

typedef struct {
	int p, d;
} goods;


void swap(goods* a, goods* b) {
	goods c = *a;
	*a = *b;
	*b = c;
	return;
}

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

void up_updata(goods* _arr, int n) {
	goods* arr = _arr - 1;
	while (n / 2 >= 1) {
		if (arr[n].p < arr[n / 2].p) {
			swap(&arr[n], &arr[n / 2]);
			n /= 2;
		}
		else break;
	}
	return;
}

void down_updata(goods* _arr, int i, int n) {
	goods* arr = _arr - 1;
	while (i * 2 <= n) {
		int ind = i, l = i * 2, r = l + 1;
		if (arr[l].p < arr[ind].p) ind = l;
		if (r <= n && arr[r].p < arr[ind].p) ind = r;
		if (ind == i) return;
		swap(&arr[ind], &arr[i]);
		i = ind;
	}
	return;
}

int main() {
	int n;
	scanf("%d", &n);
	goods* arr = (goods*)malloc(sizeof(goods) * n);
	for (int i = 0; i < n; i++) {
		scanf("%d %d", &arr[i].p, &arr[i].d);
	}
	merge(arr, 0, n);
	goods* heap = (goods*)malloc(sizeof(goods) * n);
	
	heap[0] = arr[0];
	int j = 1;
	for (int i = 1; i < n; i++) {
		if (arr[i].d > j) {
			heap[j++] = arr[i];
			up_updata(heap, j);
		}
		else if (arr[i].p > heap[0].p) {
			heap[0] = arr[i];
			down_updata(heap, 1, j);
		}
		else continue;
	}
	int ans = 0;
	for (int i = 0; i < j; i++) ans += heap[i].p;
	printf("%d", ans);
	return 0;
}

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