Under construction

Still being built. Things may change

Colorful Square

Time limit5sMemory limit512 MB

Summary
Given colored points on a plane, find the smallest axis-aligned square that contains at least one point of every color.
Level

Hard8 of 10

Topics
Binary search, Sliding window, Segment tree
Solved
No attempts yet

Problem

Given NN points P1(x1,y1),P2(x2,y2),…,PN(xN,yN)P_1(x_1, y_1), P_2(x_2, y_2), \ldots, P_N(x_N, y_N) on a plane, each point has one of KK colors. The color of each point is an integer in {1,2,…,K}\{1, 2, \ldots, K\}.

A square is called a colorful square if, for each of the KK colors, it contains at least one point of that color. Find the colorful square with the smallest side length and print that side length.

Here, squares must have all four sides horizontal or vertical. A point on the boundary of a square counts as inside it. A square with side length 0, which is a single point, also counts as a valid square.

Input

The first line contains two integers NN and KK, separated by a single space.

The next NN lines follow. The ii-th line contains three integers xix_i, yiy_i, and kik_i, separated by single spaces. They describe the point (xi,yi)(x_i, y_i) and its color kik_i.

Output

Print the answer to the problem on the first line.

Constraints

  • 2≤N≤100 0002 \le N \le 100\,000
  • 2≤K≤N2 \le K \le N
  • For every ii (1≤i≤N1 \le i \le N), xix_i and yiy_i are integers from 1 to 250 000.
  • For every color kk (1≤k≤K1 \le k \le K), at least one of the NN points has color kk.

Examples3

  1. Example 1

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

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

    Input
    4 2
    1 1 1
    1 1 1
    1 1 2
    1 1 2
    
    Expected output
    0