目录

USACO 2017 Jan Gold P1

USACO analysis

Mark Chen | 14 Nov 2020

Problem 1 Balanced Photo

Link to Problem

Problem Summary

John want to arrange his $N$ , $1\leq N \leq 100,000$ cows to take a photo. The height of $i$th cow is $h_i$. the heights of all cows are distinct. In a line, a cow is called “unbalanced” if the number of cow that is higher than it on the left is two time (or half of) the number of cow that is lower than it. Given the line of cow, give out the number of unbalanced cows in the photo.

Proposed Solution

First, we can range all the cows from high to low, and fill the array with the cow’s height.

cows = [34, 6, 23, 0, 5, 99, 2]
arr = [_ for _ in range(len(cows))]
arr.sort(key=lambda x: cows[x])

After doing this, we can initialize a new list that used to store whether a cow has been counted. The new list will be filled with 0.

l = [0] * len(cows)

After this, we will apply following steps, suppose we are dealing with the $k$th highest cow, where cows[k] = n

To decrease the time complexity of solution, we will use a data structure called Binary Index Tree (BIT) on $l$. Using BIT, we can calculate $L$, $R$, and update $l$ with time complexity of $O(\log{n})$.

  1. Calculate $L = \sum_{i = 0}^n l[i]$. Since we will process all the cows from highest to the shortest, the result of formula will be the number of cow that is higher than current cow and stands on its left.

  2. Calculate $R = k - 1 - \sum_{i = 0}^n l[i]$. Since the current cow we are dealing with is the $k$th highest cow, there are $k-1$ cows that are higher than current one. The cow that is higher than current cow and NOT on its left must stand on its right.

  3. Calculate
  4. \[\frac{\min{(L, R)}}{\max{(L, R)}}\]

If the result is greater than 2, add the number of unbalanced cow by 1.

  1. Set the value of $l[n] = 1$.

Time Complexity Analysis

Therefore, the total time complexity will be $O(n\log{n})$.


评论区