Problem:
Problem J: Tree Construction

Consider a two-dimensional space with a set of points (xi,
yi) that satisfy xi < xj
and yi > yj for all i < j.
We want to have them all connected by a directed tree whose edges go toward
either right (x positive) or upward (y positive). The
figure below shows an example tree.

Figure 1: An example tree

Write a program that finds a tree connecting all given points with the
shortest total length of edges.

Input

The input begins with a line that contains an integer n (1 <=
n <= 1000), the number of points. Then n lines follow. The
i-th line contains two integers xi and yi
(0 <= xi, yi <= 10000), which give
the coordinates of the i-th point.

Output

Print the total length of edges in a line.

Sample Input 1

5
1 5
2 4
3 3
4 2
5 1

Output for the Sample Input 1

12

Sample Input 2

1
10000 0

Output for the Sample Input 2

0

Solution in Scala (judge verdict: Accepted)

import scala.io.StdIn._
object Main extends App {
  val n = readInt()
  val points = Array.tabulate(n){_ ⇒
    val Array(x, y) = readLine.trim.split(' ').map(_.toInt)
    Point(x, y)
  }
  val memo = Array.tabulate(n){i ⇒ Array.fill(n - i){-1}}
  for (i ← 1 until n / 100) minTree(points, 0, i * 100)(memo)
  println(minTree(points, 0, n)(memo))
  def minTree(points: Array[Point], from: Int, until: Int)(implicit memo: Array[Array[Int]]): Int = {
    if (from + 1 == until) {
      0
    }else if (until - from == 2) {
      minTree(points(from), points(from + 1))
    }else {
      if (memo(from)(until - from - 1) < 0) {
        memo(from)(until - from - 1) = (from + 1 until until).map{mid ⇒ minTree(points, from, mid) + minTree(root(points, from, mid), root(points, mid, until)) + minTree(points, mid, until)}.min
      }
      memo(from)(until - from - 1)
    }
  }
  def minTree(a: Point, b: Point, c: Point): Int = {
    Math.min(minTree(root(a, b), c) + minTree(a, b), minTree(a, root(b, c)) + minTree(b, c))
  }
  def minTree(a: Point, b: Point): Int = {
    b.x - a.x + a.y - b.y
  }
  def root(points: Array[Point], from: Int, until: Int): Point = root(points(from), points(until - 1))
  def root(a: Point, b: Point): Point = {
    Point(a.x, b.y)
  }
}

case class Point(x: Int, y: Int)