This page is still under construction.

Parts of this page are still being built. What you see may change.

Fair Photography

Time limit1sMemory limit128 MB

Summary
After sorting cows by position, find the widest contiguous group containing at least K breeds with each present breed appearing equally often.
Level

Medium7 of 10

Topics
Prefix sum, Hash map
Solved
No attempts yet

Problem

FJ has NN cows (1≤N≤100 0001 \le N \le 100\,000) standing along a long one-dimensional fence. Cow ii stands at position xix_i (integer in 0…1 000 000 0000 \ldots 1\,000\,000\,000) and has breed bib_i (1…81 \ldots 8). No two cows share a position.

FJ wants a photo of a contiguous interval of cows. Every breed that appears in the photo must appear the same number of times (for example, 27 of breed 1 and 27 of breed 3 is fine, but 9 of breed 1 and 10 of breed 3 is not). At least KK breeds (K≥2K \ge 2) must appear.

Find the maximum photo size, defined as the difference between the largest and smallest positions among cows in the photo. If no valid photo exists, output −1-1.

Input

  • Line 1: NN and KK.
  • Next NN lines: xix_i and bib_i.

Output

One integer: the maximum fair photo size, or −1-1 if none exists.

Hint

Sort by position, then check each contiguous interval for equal per-breed counts.

Examples6

  1. Example 1

    Input
    9 2
    1 1
    5 1
    6 1
    9 1
    100 1
    2 2
    7 2
    3 3
    8 3
    
    Expected output
    6
    
  2. Example 2

    Input
    3 2
    1 1
    4 2
    7 1
    
    Expected output
    6
    
  3. Example 3

    Input
    4 2
    1 1
    2 1
    3 2
    4 2
    
    Expected output
    3
    
  4. Example 4

    Input
    8 2
    138 2
    262 2
    508 8
    484 7
    808 4
    97 8
    30 7
    444 1
    
    Expected output
    546
    
  5. Example 5

    Input
    12 3
    979 1
    94 2
    370 3
    754 5
    258 4
    622 1
    596 3
    442 7
    823 6
    558 8
    515 5
    923 1
    
    Expected output
    464
    
  6. Example 6

    Input
    15 2
    244 3
    379 8
    641 2
    621 1
    931 8
    266 4
    197 8
    554 8
    407 3
    238 3
    889 7
    760 1
    688 2
    164 1
    309 1
    
    Expected output
    243