2019 Dec Bronze Problem 3 Livestock Lineup
Official Problem StatementEdit
Problem StatementEdit
The USACO 965 problem, Livestock Lineup, is a classic problem of sorting. Given a list of N (1 ≤ N ≤ 10,000) cows, each with a unique ID number from 1 to N, you must arrange them in a line such that the absolute difference between the ID numbers of any two adjacent cows is as small as possible.
SolutionEdit
The solution to this problem is to sort the cows in ascending order according to their ID numbers. This can be done using a C++ implementation of the quicksort algorithm.
// C++ implementation of quicksort algorithm
void quicksort(int arr[], int left, int right) {
int i = left, j = right; int tmp; int pivot = arr[(left + right) / 2]; /* partition */ while (i <= j) { while (arr[i] < pivot) i++; while (arr[j] > pivot) j--; if (i <= j) { tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; i++; j--; } }; /* recursion */ if (left < j) quicksort(arr, left, j); if (i < right) quicksort(arr, i, right);
}