Back to Blogs
USACOCompetitive ProgrammingSimulationArraysJune 3, 2026

USACO 2024 Cannonball: Direct Simulation With State

A direct-simulation guide for tracking position, direction, power, and broken targets without losing the meaning of each state variable.

Cannonball is a direct simulation problem. These problems are not about a clever formula. They are about maintaining state carefully and applying the rules in the correct order.

Name the state variables

A good simulation begins by naming exactly what changes over time:

  • position: where the cannonball is now.
  • power: how far it moves each jump.
  • direction: left or right.
  • broken: which targets have already been broken.

If a variable cannot be explained in one sentence, debugging becomes much harder.

The simulation loop

Each iteration moves the cannonball, checks whether it is outside the field, and then applies the rule for the landing position.

while true:
    position = position + direction * power
    if position is outside:
        stop
    if spot is a target:
        break it if power is enough
    else if spot is a booster:
        increase power
        reverse direction

Why order matters

Changing direction before increasing power, or counting a broken target twice, can change the answer. Simulation problems reward careful sequencing.

Common mistakes

  • Using 0-indexing in arrays after reading 1-indexed positions without converting carefully.
  • Breaking the same target more than once.
  • Forgetting to stop when the position leaves the valid range.
  • Applying the bounce rule to target cells or the target rule to bounce cells.

Practice prompt

Make a five-position field with one booster and two targets. Start at position 2 with power 1. Trace position, power, direction, and broken target count after every jump.