Cow Lineup
Time limit1sMemory limit128 MB
Find the minimum span of x coordinates covering at least one cow of every distinct breed id.
- Level
Medium6 of 10
- Topics
- Sorting, Sliding window, Hash map, Two pointers
- Solved
- No attempts yet
Problem
A farmer wants a single photograph that includes at least one cow of every distinct breed present in the herd.
The cows stand at various positions along a line. Each cow is described by an integer position (its coordinate) and an integer breed ID. The photograph captures a contiguous range of cows along the line, and its cost equals its size — the difference between the maximum and minimum coordinates of the cows inside that range.
Compute the minimum possible cost of a photograph that contains at least one cow of every distinct breed present in the herd.
Input
- Line 1: an integer (), the number of cows.
- Lines 2 to : each line contains two space-separated positive integers, the coordinate and the breed ID of one cow. Both values are at most .
Output
- A single line with the smallest cost of a photograph that contains at least one cow of every distinct breed ID.
Hint
Suppose there are cows at positions with breed IDs respectively. The distinct breeds are , , and . The range from up to has size and contains all three distinct breeds, which is the minimum possible cost.