Greedy · straightforward
Standing where it is, the raccoon scores every uneaten item and walks to the most attractive one, then
repeats. Attractiveness is Smith's ratio rule: calories lost per second of waiting ÷ seconds of
walking to it. Food that would already be spoiled on arrival ranks below all fresh food (nearest
first). It never looks more than one step ahead.
GREEDY-RACCOON(items, den, speed)
1 here = den
2 clock = 0
3 remaining = all n items
4 route = empty list
5 while remaining is not empty
6 best = NIL
7 best_value = −∞
8 for each item j in remaining
9 travel = distance(here, j) / speed
10 value = ATTRACTIVENESS(j, travel, clock + travel)
11 if value > best_value
12 best = j
13 best_value = value
14 best_travel = travel
15 clock = clock + best_travel
16 here = position of best
17 remove best from remaining
18 append best to route
19 return route
- Time
- Θ(n²): lines 9–14 run n + (n−1) + … + 1 times
- Memory
- Θ(n)
Greedy + 2-opt · clever
Step 1: build exactly Greedy's route, but faster. All items of one food type share the
same w, so the best fish is just the nearest fish. One k-d tree per food type answers
"nearest uneaten fish?" in O(log n).
Step 2: repeatedly pick a stretch of the route and walk it backwards when that loses fewer
calories. Running totals of the stretch's walking time, weight and internal cost give an O(1) estimate
of each move (exact while no item crosses its shelf life); moves that look good are confirmed with the
exact score, so a flip is only kept if it really helps.
TWO-OPT-RACCOON(items, den, L, P)
1 route = GREEDY-KD(items, den)
2 repeat at most P times
3 improved = false
4 for i = 1 to n
5 for j = i+1 to min(n, i+L−1)
6 estimate = estimated change if
route[i..j] is reversed ▹ O(1)
7 if estimate < 0 and the exact loss
after reversing is lower ▹ Θ(n)
8 reverse route[i..j] ▹ O(L)
9 recompute arrival times ▹ Θ(n)
10 improved = true
11 if not improved: stop
12 return route
- Time
- O(n log² n + P·n·L + V·n) expected, with L = 50 and P = 20 fixed and
V = moves checked exactly (accepted flips included). V grows with n, so in practice this is
about n², the same order as Greedy. 2-opt's advantage is the score, not asymptotic speed.
- Memory
- Θ(n)