Silver
Batch
Editorial available
Stall Shuffle
/stall-shuffle
Version
v1
Published
Apr 23, 2026, 10:56 PM
Updated
Apr 23, 2026, 10:56 PM
Testsets
1
Statement
Rendered as plain statement text from the published version.
# Stall Shuffle
## Problem
Bessie is organizing a barn dance, and she needs to assign each cow to a stall. There are N cows and N stalls, each at a specific position on the barn floor. Each cow must be assigned to exactly one stall, and each stall can hold exactly one cow.
The cost of assigning a cow to a stall is the absolute distance between their positions. Your goal is to find an assignment that minimizes the total distance traveled by all cows.
## Input
The first line contains a single integer N (1 ≤ N ≤ 100,000), the number of cows and stalls.
The second line contains N integers representing the positions of the cows.
The third line contains N integers representing the positions of the stalls.
## Output
Print a single integer: the minimum total distance required to assign all cows to stalls.
## Constraints
- 1 ≤ N ≤ 100,000
- 0 ≤ position ≤ 1,000,000
## Sample
**Input:**
```
3
1 5 9
2 6 8
```
**Output:**
```
3
```
**Explanation:**
Sort both arrays: cows = [1, 5, 9], stalls = [2, 6, 8].
Assign in sorted order:
- Cow at position 1 → Stall at position 2: distance = |1 - 2| = 1
- Cow at position 5 → Stall at position 6: distance = |5 - 6| = 1
- Cow at position 9 → Stall at position 8: distance = |9 - 8| = 1
Total distance = 1 + 1 + 1 = 3