#P3162. Minimizing Assembly Transportation Cost

    ID: 16419 Type: Default 1000ms 256MiB

Minimizing Assembly Transportation Cost

Minimizing Assembly Transportation Cost

You are given m production workshops located on a number line. There are n types of parts, numbered from \(1\) to \(n\). The \(i\)th workshop is located at coordinate \(x_i\) and produces part type \(p_i\) (where \(1 \le p_i \le n\)). You are required to build an assembly workshop at some position \(a\) on the number line so that all parts can be assembled together.

For each part type \(x\), define its transportation cost as:

\[ \text{cost}_x = \min_{\substack{i \text{ such that } p_i=x}} (a - x_i)^2, \]

Your goal is to choose a position \(a\) that minimizes the total cost:

\[ \text{Total Cost} = \sum_{x=1}^{n} \text{cost}_x. \]

It is guaranteed that for every part type \(x \in [1,n]\), there is at least one workshop producing that type.

inputFormat

The first line contains two integers \(m\) and \(n\) (the number of production workshops and the number of types of parts respectively).

Each of the next \(m\) lines contains two integers \(x_i\) and \(p_i\), representing the coordinate of the workshop and the type of part it produces.

You may assume that for every type \(x\) between 1 and \(n\), there is at least one workshop with \(p_i=x\).

outputFormat

Output a single number, which is the minimum possible total cost \(\sum_{x=1}^{n} \text{cost}_x\).

sample

3 2
0 1
10 2
20 1
50