USACO 1.3 Barn Repair (快排+贪心)

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

#define MAX_STALLS 200

int numOfBoards, numOfStalls, numOfCows;
int stallOccupied[MAX_STALLS + 1];
int arrayOfIntervals[MAX_STALLS];
int numOfIntervals;

void sort(int array[], int first, int last){
	while (first < last){
		int pivotValue = array[first];
		int left = first;
		int right = last;
		while (left < right){
			while (left < right && array[right] >= pivotValue)
				right--;
			array[left] = array[right];
			while (left < right && array[left] <= pivotValue)
				left++;
			array[right] = array[left];
		}
		array[left] = pivotValue;
		int pivot = left;
		sort(array, first, pivot);
		first = pivot + 1;
	}
}

int main(){
#if DEBUG
	int testCase;
	for (testCase = 1; testCase <= TESTCASES; testCase++){
		char inputFileName[20] = "barn1.inX";
		inputFileName[8] = '1' +  (testCase - 1);
		freopen(inputFileName, "r", stdin);
		printf("\n#%d\n", testCase);
#endif

	scanf("%d %d %d", &numOfBoards, &numOfStalls, &numOfCows);
	int cow;
	for (cow = 1; cow <= numOfCows; cow++)
		scanf("%d", &stallOccupied[cow]);

	if (numOfBoards >= numOfCows){
		printf("%d\n", numOfCows);
#if DEBUG
		continue;
#else
		return 0;
#endif
	}

	sort(stallOccupied, 1, numOfCows);

	numOfIntervals = 0;
	for (cow = 1; cow < numOfCows; cow++)
		arrayOfIntervals[++numOfIntervals] = stallOccupied[cow + 1] - stallOccupied[cow] - 1;
	sort(arrayOfIntervals, 1, numOfIntervals);

	int numOfIntervalsUncovered = numOfBoards - 1;	

	int stallsUncovered = 0;
	while (numOfIntervalsUncovered--)
		stallsUncovered += arrayOfIntervals[numOfIntervals--];

	int stallsBlocked = stallOccupied[numOfCows]  - stallOccupied[1] + 1 - stallsUncovered;
	printf("%d\n", stallsBlocked);

#if DEBUG
	}
#endif
	return 0;	
}

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