import scala.io.StdIn class BIT(size:Int) { val n:Int = size val buf:Array[Int] = Array.fill(n+1)(0) def add(x:Int,v:Int) = { var y = x while(y<=n){ buf(y)+=v y+=(y& -y) } } def sum(x:Int):Int = { var s = 0 var y = x while (y>0){ s+=buf(y) y&=y-1 } return s } } object Main extends App { val n: Int = StdIn.readInt() val l: Array[Int] = StdIn.readLine().split(" ").map(_.toInt) val bl, br: BIT = new BIT(n) //座標圧縮 val z: Map[Int, Int] = l.sorted.distinct.zipWithIndex.toMap val t: Array[Int] = l.map(z(_) + 1) //最初は全部右にある for (v <- t) br.add(v, 1) val cnt: Long = t.zipWithIndex.map { case (v: Int, i: Int) => bl.add(v, 1) br.add(v, -1) //左右の自分より小さい数同士、大きい数同士を掛けた数がパターン数 bl.sum(v - 1) * br.sum(v - 1) + (i + 1 - bl.sum(v)) * (n - i - 1 - br.sum(v)) }.sum //左右が同じ数になるパターンを引く 解説(http://ideone.com/qVicVL)の通り val exclude: Long = (0 until n).groupBy(t(_)).values.flatMap(a => (1 until a.length).map(i => i * (a.length - i) * (a(i) - a(i - 1) - 1))).sum println(cnt - exclude) }