Problem:
Score : 600 points

Problem Statement

There are N cities in Republic of AtCoder. The size of the i-th city is A_{i}.
Takahashi would like to build N-1 bidirectional roads connecting two cities so that any city can be reached from any other city by using these roads.

Assume that the cost of building a road connecting the i-th city and the j-th city is |i-j| \times D + A_{i} + A_{j}.
For Takahashi, find the minimum possible total cost to achieve the objective.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq D \leq 10^9

1 \leq A_{i} \leq 10^9

A_{i} and D are integers.

Input

Input is given from Standard Input in the following format:

N D
A_1 A_2 ... A_N

Output

Print the minimum possible total cost.

Sample Input 1

3 1
1 100 1

Sample Output 1

106

This cost can be achieved by, for example, building roads connecting City 1, 2 and City 1, 3.

Sample Input 2

3 1000
1 100 1

Sample Output 2

2202

Sample Input 3

6 14
25 171 7 1 17 162

Sample Output 3

497

Sample Input 4

12 5
43 94 27 3 69 99 56 25 8 15 46 8

Sample Output 4

658

Solution in Scala (2.11.7) (judge verdict: Wrong Answer)


object Main extends App {

  import scala.io.StdIn._

  val Array(n, d) = readLine.trim.split(' ').map(_.toInt)
  val cities = readLine.trim.split(' ').map(_.toLong).zipWithIndex
  println(minCost(cities.reverse.toList))
  def minCost(cities: List[(Long, Int)]): Long = {
    def sub(list: List[(Long, Int)], current: Long, result: Long = 0): Long = {
      list match {
        case (a, b)::t if a + b * d > current ⇒ sub(t, current, current + a - b * d + result)
        case (a, b)::t ⇒ sub(t, a + b * d, current + a - b * d + result)
        case Nil ⇒ result
      }
    }
    sub(cities.tail, cities.head.let{case (a, b) ⇒ a + b * d})
  }

  class UnionFindTree{
    private var mParent: Option[UnionFindTree] = None
    private var mSize: Int = 1
    private def parent: UnionFindTree = {
      mParent.map{_.parent} match {
        case None ⇒ this
        case c@Some(p) ⇒
          mParent = c
          p
      }
    }
    def isSameUnion(that: UnionFindTree): Boolean = {
      parent == that.parent
    }
    def merge(that: UnionFindTree): Unit = {
      if (!isSameUnion(that)){
        val p = parent
        val tp = that.parent
        if (p.mSize > tp.mSize){
          tp.mParent = Some(p)
          p.mSize += tp.mSize
        }else {
          p.mParent = Some(tp)
          tp.mSize += p.mSize
        }
      }
    }
  }
  implicit class Extension[T](value :T){
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
    @inline
    def also(@inline func: T ⇒ Unit): T = {func(value); value}
  }
}