Arrays

3.6

18 votes
Ad-Hoc, Data Structures, Heaps, Medium, Trees, 普通-難しい
Problem

Note that time limit has been increased to 3 sec

Mike has 3 arrays a,b,c of length n and a number k. He wants to find minimal value of
maxni=1(((ai+t)modk)+((bi+t)modk)+((ci+t)modk))

over all non-negative integer values of t.

Input

The first line contains two numbers n and k (1n3×105,1k108).

Each of the next n lines contains 3 numbers - ai,bi,ci (0ai,bi,ci<k).

Output

Output the minimal value achievable.

Sample Input
3 6
1 4 2
3 5 0
3 3 5
Sample Output
8
Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

For t=4 we have that and this is the minimal value we chan achieve.

Editor Image

?