目录

USACO 2017 Dec Gold P1

USACO analysis

Mark Chen | 10 Dec 2020

Problem 1. A Pie For A Pie

Problem Description

Bessie and Elsie have each baked $N$ pies and each pie has two tasty value - one from Bessie and one from Elsie. In the begining, Bessie gave a pie to Elsie.

If Elsie receive a pie that she think has a tasty value of $n$, she will try to give back Bessie one of her pie that has a tasty value that is in range $n \leq n’ \leq n + D$. If such a pie does not exist, she will ‘exile’ herself.

If Bessie receive a pie from Elsie, the same thing will happen.

Such a cycle will continue, until one of the cow exile herself or they receive a pie that has a tasty value of 0 for them. For each input case, we will solve the minimum number of pies that could be gifted in a happy gift exchange started with Bessie’s pie $i$. If no gift exchange with pie $i$ is happy, then we should print out a single integer $-1$ instead.

:warning: Notice that a pie can only be sent once and the cow can’t send back the pie the other cow sent.

Proposed Solution

In this question, we can use the bottom-to-up method. Instead of checking how many pies will be exchanged for a given beginning pie, we can search reversely from the end point to the start point. In this way, we can only apply one search on all the pie and get the result with time complexity of $O(1)$ for each query.

The actual program will work like this

  1. Sort all the pies
  2. Search from pies that have a taste value of 0 both for Bessie and Elsie.
  3. While searching, store the number of pies exchanged from 0 of Bessie and Elsie.
  4. For each query, find the number stored in the corresponding index.

Time Complexity Analysis

The time complexity for steps above will be -

  1. $O(n\log{n})$
  2. $O(n)$
  3. $O(1)$ for each query and total time complexity will be $O(n)$.

评论区