USACO 1.3 Mixing Milk (快排+贪心)

#include <stdio.h>
#define DEBUG 0
#define TESTCASES 9

#define MAX_FARMERS 5000
int milkNeeded;
int numOfFarmers;
typedef struct Farmer{
	int price;
	int milk;
}Farmer;
Farmer farmers[MAX_FARMERS + 1];

void sortFarmersAccordingToPrice(int first, int last){
	while (first < last){
		Farmer pivotFarmer = farmers[first];
		int pivotPrice = farmers[first].price;
		int left = first;
		int right = last;
		while (left < right){
			while (left < right && farmers[right].price >= pivotPrice)
			right--;
			farmers[left] = farmers[right];
			while (left < right && farmers[left].price <= pivotPrice)
			left++;
			farmers[right] = farmers[left];
		}
		farmers[left] = pivotFarmer;
		int pivot = left;
		sortFarmersAccordingToPrice(first, pivot);
		first = pivot + 1;		
	}
}
int mix(){
	int minPrice = 0;
	int milkMixed = 0;
	int farmer;
	for (farmer = 1; farmer <= numOfFarmers; farmer++){
		if (milkMixed  + farmers[farmer].milk >= milkNeeded){
			minPrice += farmers[farmer].price * (milkNeeded - milkMixed);
			break;
		} else {
			milkMixed += farmers[farmer].milk;
			minPrice += farmers[farmer].price * farmers[farmer].milk;
		}			
	}
	return minPrice;
}

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "milk.inX";
		inputFileName[7] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif
	
	scanf("%d %d", &milkNeeded, &numOfFarmers);
	int farmer;
	for (farmer = 1; farmer <= numOfFarmers; farmer++)
		scanf("%d %d", &farmers[farmer].price, &farmers[farmer].milk);

	sortFarmersAccordingToPrice(1, numOfFarmers);

	int minPrice = mix();

	printf("%d\n", minPrice);

#if DEBUG
	}
#endif
	return 0;
	
}

你可能感兴趣的:(USACO,快排,贪心,1.3,milk,Mixing)