Table of Contents

SolutionImplementation

Solution

Let's define lowestOps[a][b]\texttt{lowestOps}[a][b] as the minimum number of operations to see if each horse is in the stables or not, given that we only consider horses in the interval (stableHorses[a],stableHorses[b])(\texttt{stableHorses[a]}, \texttt{stableHorses[b]}), with stableHorses\texttt{stableHorses} being a sorted list of all the horses that are in the stables.

Why use an open interval? It's to account for the horses with ID's that aren't contained in the range of the ID's of the horses of the stable. For example, if we had a horse with ID 44, and the horses in the stables were [6,7,10][6, 7, 10], then there would be no way for lowestOps\texttt{lowestOps} to account for that horse.

To solve this, we can add two more hypothetical horses that are just out of bounds of all the other horses: one at the front and one at the end. This along with the open interval ensures that we can account for all horses excluding the hypothetical ones we've added.

Then, to calculate the value for an interval, we go through all possible roots we can use for the tree of that interval. If we're calculating lowestOps[a][b]\texttt{lowestOps}[a][b] with ba3b-a\geq3 and we're using a root cc (a<c<ba<c<b), then we have the following recurrence relation:

lowestOps[a][b]=lowestOps[a][c]+lowestOps[c][b]+(stableHorses[b]stableHorses[a]1)\texttt{lowestOps}[a][b]=\texttt{lowestOps}[a][c]+\texttt{lowestOps}[c][b]+(\texttt{stableHorses}[b]-\texttt{stableHorses}[a]-1)

Implementation

Time Complexity: O(N3)\mathcal{O}(N^3)

C++

#include <algorithm>
#include <cassert>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
int main() {

Java

import java.io.*;
import java.util.Arrays;
public final class genghis {
public static void main(String[] args) throws IOException {
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
int horseNum = Integer.parseInt(read.readLine());
int stableNum = Integer.parseInt(read.readLine());
int[] stableHorses = new int[stableNum + 2];
for (int i = 1; i <= stableNum; i++) {

Python

horse_num = int(input())
stable_num = int(input())
stable_horses = sorted([0, horse_num + 1] + [int(input()) for _ in range(stable_num)])
"""
lowest_ops[i][j] = min operations if we only consider horses
from that exist in the index interval (i, j)
ex: lowest_ops[1][4] and stable_horses = [0, 1, 3, 7, 10, 11]
means that we only consider horses from (1, 10)
"""

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!