Problem:
Score: 500 points

Problem Statement

Given is a permutation P of \{1, 2, \ldots, N\}.

For a pair (L, R) (1 \le L \lt R \le N), let X_{L, R} be the second largest value among P_L, P_{L+1}, \ldots, P_R.

Find \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Constraints

2 \le N \le 10^5

1 \le P_i \le N

P_i \neq P_j (i \neq j)

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N

Output

Print \displaystyle \sum_{L=1}^{N-1} \sum_{R=L+1}^{N} X_{L,R}.

Sample Input 1

3
2 3 1

Sample Output 1

5

X_{1, 2} = 2, X_{1, 3} = 2, and X_{2, 3} = 1, so the sum is 2 + 2 + 1 = 5.

Sample Input 2

5
1 2 3 4 5

Sample Output 2

30

Sample Input 3

8
8 2 7 3 4 5 6 1

Sample Output 3

136

Solution in Scala (2.11.7) (judge verdict: Accepted)

import java.io._
import java.util.StringTokenizer
import scala.util.control.Breaks.{breakable,break}
import scala.collection.mutable.{Map, Stack, Queue, PriorityQueue, Set}

object Main extends App {
  val in = new InputReader(System.in)
  val pw = new PrintWriter(System.out)

  val N = in.next().toInt
  val P = new Array[Int](N+1)
  val indexMap = new Array[Int](N+1)
  for (i <- 1 to N) {
    P(i) = in.next().toInt
    indexMap(P(i)) = i
  }

  //
  val bit = new BIT(N+1)
  bit.add(N+1, 1)

  // 条件を満たす最大の値を返す
  def binarySearchMax(_min: Int, _max: Int, n: Int): Int = {
    def check(i: Int): Boolean = bit.sum(i) <= n

    def func(min: Int, max: Int): Int = {
      val mid: Int = (max + min) / 2
        (max - min) match{
        case 0 | 1 =>
          check(max) match{
            case true  => max
            case false => min
          }
        case _ =>
          (check(mid)) match{
            case true  => func(mid, max)
            case false => func(min, mid)
          }
      }
    }

    func(_min, _max)
  }

  // 条件を満たす最小の値を返す
  def binarySearchMin(_min: Int, _max: Int, n: Int): Int = {
    def check(i: Int): Boolean = bit.sum(i) >= n

    def func(min: Int, max: Int): Int = {
      val mid: Int = (max + min) / 2
        (max - min) match{
        case 0 | 1 =>
          check(min) match{
            case true  => min
            case false => max
          }
        case _ =>
          (check(mid)) match{
            case true  => func(min, mid)
            case false => func(mid, max)
          }
      }
    }

    func(_min, _max)
  }

  var ans = 0L
  for (k <- (1 to N).reverse) {
    val i = indexMap(k)

    if (k < N) {
      val now = bit.sum(i)
      val l1 = binarySearchMin(0, i, now)
      val r1 = binarySearchMin(i, N+1, now+1)

      // println(s"$k: $i")
      if (now > 0) { // 左に自分より大きい値が存在する
        val l2 = if (bit.sum(1) < now) binarySearchMin(0, i, now-1) else 0
        val l = l1 - l2
        val r = (r1-1) - (i-1)
        val hoge = (l * r).toLong * k

        ans += hoge
      }
      if (bit.sum(N) > now) { // 右に自分より大きい値が存在する
        val r2 = if (bit.sum(N) >= now+2) binarySearchMin(i, N, now+2) else N+1
        val l = i - l1
        val r = r2 - r1
        // println(s"r1: $r1, r2: $r2, r: $r")
        val hoge = (l * r).toLong * k
        //println(hoge)
        //println(l, r)
        ans += hoge
      }
    }

    bit.add(i, 1)
  }

  println(ans)
}

// [1, n]
// n is num of element
class BIT(n: Int) {
  val ar = new Array[Int](n+1)

  // sum of [1, i]
  def sum(i: Int): Int = {
    def func(i: Int, res: Int): Int = {
      if(i <= 0) res
      else func(i - (i & -i), res + ar(i))
    }
    func(i, 0)
  }

  // add x to i-th element
  def add(i: Int, x: Int): Unit = {
    def func(i: Int): Unit = {
      if(i <= n) {
        ar(i) += x
        func(i + (i & -i))
      }
    }
    func(i)
  }
}


object Sub {
  def print2DimArray[A](mat: Array[Array[A]]): Unit = {
    mat.foreach(lin => println(lin.deep))
  }
}

class InputReader(stream: InputStream) {
  private[this] val reader = new BufferedReader(new InputStreamReader(stream))
  private[this] var tokenizer: StringTokenizer = new StringTokenizer(reader.readLine())
  def next(): String = {
    while (!tokenizer.hasMoreTokens()) {
      tokenizer = new StringTokenizer(reader.readLine())
    }
    tokenizer.nextToken()
  }
}