Vasya's house is situated in a forest, and there is a mushroom glade near it. The glade consists of two rows, each of which can be divided into n consecutive cells. For each cell Vasya knows how fast the mushrooms grow in this cell (more formally, how many grams of mushrooms grow in this cell each minute). Vasya spends exactly one minute to move to some adjacent cell. Vasya cannot leave the glade. Two cells are considered adjacent if they share a common side. When Vasya enters some cell, he instantly collects all the mushrooms growing there.Vasya begins his journey in the left upper cell. Every minute Vasya must move to some adjacent cell, he cannot wait for the mushrooms to grow. He wants to visit all the cells exactly once and maximize the total weight of the collected mushrooms. Initially, all mushrooms have a weight of 0. Note that Vasya doesn't need to return to the starting cell.Help Vasya! Calculate the maximum total weight of mushrooms he can collect.

The first line contains the number n (1 ≤ n ≤ 3·105) — the length of the glade. The second line contains n numbers a1, a2, ..., an (1 ≤ ai ≤ 106) — the growth rate of mushrooms in the first row of the glade. The third line contains n numbers b1, b2, ..., bn (1 ≤ bi ≤ 106) is the growth rate of mushrooms in the second row of the glade.

Output one number — the maximum total weight of mushrooms that Vasya can collect by choosing the optimal route. Pay attention that Vasya must visit every cell of the glade exactly once.

NoteIn the first test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·2 + 2·3 + 3·4 + 4·5 + 5·6 = 70.In the second test case, the optimal route is as follows:    Thus, the collected weight of mushrooms will be 0·1 + 1·10 + 2·100 + 3·1000 + 4·10000 + 5·100000 = 543210.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val A = Array(na(N), na(N))
    var ans = 0L

    val S = Array.ofDim[Long](N + 1)
    REP_r(N) { i =>
      S(i) = S(i + 1) + A(0)(i) + A(1)(i)
    }
    val tour = Array.ofDim[Long](2, N + 1) // 0-indexed, ここからぐぐっと回った時に、係数0スタートで累積した値
    REP(2) { x =>
      REP_r(N) { i =>
        val end = A(x ^ 1)(i).toLong * ((N - i) * 2 - 1)
        tour(x)(i) = tour(x)(i + 1) + S(i + 1) + end
      }
    }

    var past = 0L
    REP(N) { i =>
      val x = i % 2
      val v0 = i * 2
      val v1 = v0 + 1
      ans = max(ans, past + tour(x)(i) + S(i) * v0)
      past += A(x)(i).toLong * v0 + A(x ^ 1)(i).toLong * v1
    }

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val X = Array.ofDim[Long](2, N)
    rep(N) (i => X(0)(i) = ni())
    rep(N) (i => X(1)(i) = ni())

    val cum = Array.ofDim[Long](N + 1)
    rep(N) { i =>
      cum(i + 1) = cum(i) + X(0)(i) + X(1)(i)
    }

    def S(i: Int): Long = cum(N) - cum(i)

    def initOutside(i: Int, off: Int) = {
      val x = i % 2
      var res = 0L
      rep(N - i) { j =>
        res += X(x)(j + i) * (j + off)
      }
      rep(N - i) { j =>
        res += X(x ^ 1)(N - 1 - j) * (N - i + j + off)
      }
      res
    }

    val prevOutside = Array.ofDim[Long](2)
    prevOutside(0) = initOutside(0, 0)
    prevOutside(1) = initOutside(1, 2)

    // i: [0, N-1] 横の位置
    def collectOutside(i: Int): Long = {
      val x = i % 2
      if (i < 2) {
        prevOutside(x)
      } else {
        val k = (N - i + 2) * 2 - 1
        val off = (i - 2) * 2
        val res = prevOutside(x) +
          2 * S(i) -
          off * X(x)(i - 2) -
          (off + 1) * X(x)(i - 1) -
          (off + k) * X(x ^ 1)(i - 2) -
          (off + k - 1) * X(x ^ 1)(i - 1)
        prevOutside(x) = res
        res
      }
    }

    def step(i: Int) = {
      val x = i % 2
      i * 2 * X(x)(i) + (i * 2 + 1) * X(x ^ 1)(i)
    }

    var ans = 0L
    var cur = 0L
    rep(N - 1) { i =>
      ans = max(ans, collectOutside(i) + cur)
      cur += step(i)
    }
    ans = max(ans, cur + step(N - 1))

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object Main {
import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val field = Array.ofDim[Int](2, n)
        val sum = Array.ofDim[Long](2, n)
        val sum123 = Array.ofDim[Long](2, n)
        val sum321 = Array.ofDim[Long](2, n)
        for(i <- 0 until 2) {
            for(j <- 0 until n) {
                val a = nextInt
                field(i)(j) = a
                sum(i)(j) = a
                if(j > 0) sum(i)(j) += sum(i)(j - 1)
            }
        }

        for(i <- 0 until 2) {
            for(j <- n - 1 to 0 by -1) {
                sum321(i)(j) = (n - 1  - j).toLong * field(i)(j)
                sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)
                if(j < n - 1) {
                    sum321(i)(j) += sum321(i)(j + 1)
                    sum123(i)(j) += sum123(i)(j + 1)
                }
            }
        }

        var res = 0L
        var line = 0
        var time = 0L
        var acc = 0L
        def getSum(line: Int, i: Int) = {
            if(i < 0) 0 else sum(line)(i)
        }
        for(i <- 0 until n) {
            val ol = other(line)
            val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +
                sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))
            res = math.max(res, tmp + acc)
            acc += field(line)(i)*time + field(ol)(i)*(time + 1)

            time += 2
            line = ol
        }

        println(math.max(res, acc))
    }

    def other(line: Int) = (line + 1) % 2

  }

}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val X = Array.ofDim[Int](2, N)
    rep(N) (i => X(0)(i) = ni())
    rep(N) (i => X(1)(i) = ni())

    val cum = Array.ofDim[Long](N + 1)
    rep(N - 1) { i =>
      cum(i + 1) = cum(i) + X(0)(i + 1) + X(1)(i + 1)
    }

    def S(i: Int): Long = cum(N - i)

    def initOutside(i: Int, off: Int) = {
      val x = i % 2
      var res = 0L
      rep(N - i) { j =>
        res += X(x)(j + i) * (j + off)
      }
      rep(N - i) { j =>
        res += X(x ^ 1)(N - 1 - j) * (N - i + j + off)
      }
      res
    }

    val prevOutside = Array.ofDim[Long](2)
    prevOutside(0) = initOutside(0, 0)
    prevOutside(1) = initOutside(1, 2)

    // i: [0, N-1] 横の位置
    def collectOutside(i: Int): Long = {
      val x = i % 2
      if (i < 2) {
        prevOutside(x)
      } else {
        val k = (N - i + 2) * 2 - 1
        val res = prevOutside(x) +
          2 * S(i) +
          2 * X(x)(i - 1) -
          (k - 2) * X(x ^ 1)(i - 2) -
          (k - 4) * X(x ^ 1)(i - 1)
        prevOutside(x) = res
        res
      }
    }

    def step(i: Int) = {
      val x = i % 2
      i * 2 * X(x)(i) + (i * 2 + 1) * X(x ^ 1)(i)
    }

    var ans = 0L
    var cur = 0L
    rep(N - 1) { i =>
      ans = max(ans, collectOutside(i) + cur)
      cur += step(i)
    }
    ans = max(ans, cur + step(N - 1))

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val A = Array(na(N), na(N))
    var ans = 0L

    val S = Array.ofDim[Long](N + 1)
    REP_r(N) { i =>
      S(i) = S(i + 1) + A(0)(i) + A(1)(i)
    }
    val tour = Array.ofDim[Long](2, N + 1) // 0-indexed, ここからぐぐっと回った時に、係数0スタートで累積した値
    REP(2) { x =>
      REP_r(N) { i =>
        val end = A(x ^ 1)(i) * ((N - i) * 2 - 1)
        tour(x)(i) = tour(x)(i + 1) + S(i + 1) + end
      }
    }

    var past = 0L
    REP(N) { i =>
      val x = i % 2
      val v0 = i * 2
      val v1 = v0 + 1
      ans = max(ans, past + tour(x)(i) + S(i) * v0)
      past += A(x)(i).toLong * v0 + A(x ^ 1)(i).toLong * v1
    }

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val A = Array(na(N), na(N))
    var ans = 0L

    val S = Array.ofDim[Long](N + 1)
    REP_r(N) { i =>
      S(i) = S(i + 1) + A(0)(i) + A(1)(i)
    }
    val tour = Array.ofDim[Long](2, N + 1) // 0-indexed, ここからぐぐっと回った時に、係数0スタートで累積した値
    REP(2) { x =>
      REP_r(N) { i =>
        val end = A(x ^ 1)(i) * ((N - i) * 2 - 1)
        tour(x)(i) = tour(x)(i + 1) + S(i + 1) + end
      }
    }

    var past = 0L
    REP(N) { i =>
      val x = i % 2
      val v0 = i * 2
      val v1 = v0 + 1
      ans = max(ans, past + tour(x)(i) + S(i) * v0)
      past += A(x)(i) * v0 + A(x ^ 1)(i) * v1
    }

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    REP(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    REP(n) { i =>
      REP(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    REP(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N = ni()
    val X = Array.ofDim[Int](2, N)
    rep(N) (i => X(0)(i) = ni())
    rep(N) (i => X(1)(i) = ni())

    val cum = Array.ofDim[Long](N + 1)
    rep(N) { i =>
      cum(i + 1) = cum(i) + X(0)(i) + X(1)(i)
    }

    def S(i: Int): Long = cum(N) - cum(i)

    def initOutside(i: Int, off: Int) = {
      val x = i % 2
      var res = 0L
      rep(N - i) { j =>
        res += X(x)(j + i) * (j + off)
      }
      rep(N - i) { j =>
        res += X(x ^ 1)(N - 1 - j) * (N - i + j + off)
      }
      res
    }

    val prevOutside = Array.ofDim[Long](2)
    prevOutside(0) = initOutside(0, 0)
    prevOutside(1) = initOutside(1, 2)

    // i: [0, N-1] 横の位置
    def collectOutside(i: Int): Long = {
      val x = i % 2
      if (i < 2) {
        prevOutside(x)
      } else {
        val k = (N - i + 2) * 2 - 1
        val off = (i - 2) * 2
        val res = prevOutside(x) +
          2 * S(i) -
          off * X(x)(i - 2) -
          (off + 1) * X(x)(i - 1) -
          (off + k) * X(x ^ 1)(i - 2) -
          (off + k - 1) * X(x ^ 1)(i - 1)
        prevOutside(x) = res
        res
      }
    }

    def step(i: Int) = {
      val x = i % 2
      i * 2 * X(x)(i) + (i * 2 + 1) * X(x ^ 1)(i)
    }

    var ans = 0L
    var cur = 0L
    rep(N - 1) { i =>
      ans = max(ans, collectOutside(i) + cur)
      cur += step(i)
    }
    ans = max(ans, cur + step(N - 1))

    out.println(ans)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object Main {
import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val field = Array.ofDim[Int](2, n)
        val sum = Array.ofDim[Long](2, n)
        val sum123 = Array.ofDim[Long](2, n)
        val sum321 = Array.ofDim[Long](2, n)
        for(i <- 0 until 2) {
            for(j <- 0 until n) {
                val a = nextInt
                field(i)(j) = a
                sum(i)(j) = a
                if(j > 0) sum(i)(j) += sum(i)(j - 1)
            }
        }

        for(i <- 0 until 2) {
            for(j <- n - 1 to 0 by -1) {
                sum321(i)(j) = (n - 1  - j) * field(i)(j)
                sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)
                if(j < n - 1) {
                    sum321(i)(j) += sum321(i)(j + 1)
                    sum123(i)(j) += sum123(i)(j + 1)
                }
            }
        }

        var res = 0L
        var line = 0
        var time = 0L
        var acc = 0L
        def getSum(line: Int, i: Int) = {
            if(i < 0) 0 else sum(line)(i)
        }
        for(i <- 0 until n) {
            val ol = other(line)
            val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +
                sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))
            res = math.max(res, tmp + acc)
            acc += field(line)(i)*time + field(ol)(i)*(time + 1)

            time += 2
            line = ol
        }

        println(math.max(res, acc))
    }

    def other(line: Int) = (line + 1) % 2

  }

}

object Main {
import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val field = Array.ofDim[Int](2, n)
        val sum = Array.ofDim[Long](2, n)
        val sum123 = Array.ofDim[Long](2, n)
        val sum321 = Array.ofDim[Long](2, n)
        for(i <- 0 until 2) {
            for(j <- 0 until n) {
                val a = nextInt
                field(i)(j) = a
                sum(i)(j) = a
                if(j > 0) sum(i)(j) += sum(i)(j - 1)
            }
        }

        for(i <- 0 until 2) {
            for(j <- n - 1 to 0 by -1) {
                sum321(i)(j) = (n - 1  - j) * field(i)(j)
                sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)
                if(j < n - 1) {
                    sum321(i)(j) += sum321(i)(j + 1)
                    sum123(i)(j) += sum123(i)(j + 1)
                }
            }
        }

        var res = 0L
        var line = 0
        var time = 0
        var acc = 0L
        def getSum(line: Int, i: Int) = {
            if(i < 0) 0 else sum(line)(i)
        }
        for(i <- 0 until n) {
            val ol = other(line)
            val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +
                sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))
            res = math.max(res, tmp + acc)
            acc += field(line)(i)*time + field(ol)(i)*(time + 1)

            time += 2
            line = ol
        }

        println(math.max(res, acc))
    }

    def other(line: Int) = (line + 1) % 2

  }

}

object Main {
import java.io._
import java.util.Scanner

import collection.mutable.HashMap
import scala.collection.{SortedSet, mutable}
import scala.util.Random
  protected val EPS = 1e-11

  private def default = (
    new StreamTokenizer(new InputStreamReader(System.in)),
    new Scanner(System.in),
    new PrintWriter(System.out)
  )

  val (in, ins, out) = {
    try {
      if (sys.props.contains("xDx")) {
        (
          new StreamTokenizer(new FileReader("input.txt")),
          new Scanner(new FileReader("input.txt")),
          new PrintWriter(new FileWriter("output.txt"))
        )
      } else {
        default
      }
    } catch {
      case _: Throwable => default
    }
  }

  private def nextInt = {
    in.nextToken
    in.nval.toInt
  }

  private def nextLong = {
    in.nextToken
    in.nval.toLong
  }

  private def nextDouble = {
    in.nextToken
    in.nval
  }

  private def nextString = {
    in.nextToken
    in.sval
  }

  private def nextChar = {
    in.nextToken
    in.ttype.toChar
  }

  def main(args: Array[String]): Unit = {
    try {
      new Run().run()
    } catch {
      case e: Throwable =>
        throw new RuntimeException(e)
    } finally out.close()
  }

  class Run {
    import collection.breakOut
    def run(): Unit = {
        val n = nextInt
        val field = Array.ofDim[Int](2, n)
        val sum = Array.ofDim[Long](2, n)
        val sum123 = Array.ofDim[Long](2, n)
        val sum321 = Array.ofDim[Long](2, n)
        for(i <- 0 until 2) {
            for(j <- 0 until n) {
                val a = nextInt
                field(i)(j) = a
                sum(i)(j) = a
                if(j > 0) sum(i)(j) += sum(i)(j - 1)
            }
        }

        for(i <- 0 until 2) {
            for(j <- n - 1 to 0 by -1) {
                sum321(i)(j) = (n - 1  - j) * field(i)(j)
                sum123(i)(j) = sum(i)(n - 1) - sum(i)(j)
                if(j < n - 1) {
                    sum321(i)(j) += sum321(i)(j + 1)
                    sum123(i)(j) += sum123(i)(j + 1)
                }
            }
        }

        var res = 0L
        var line = 0
        var time = 0
        var acc = 0L
        def getSum(line: Int, i: Int) = {
            if(i < 0) 0 else sum(line)(i)
        }
        for(i <- 0 until n) {
            val ol = other(line)
            val tmp = sum123(line)(i) + time * (sum(line)(n - 1) - getSum(line, i - 1)) +
                sum321(ol)(i) + (time + n - i)*(sum(ol)(n - 1) - getSum(ol, i - 1))
            res = math.max(res, tmp)
            acc += field(line)(i)*time + field(ol)(i)*(time + 1)

            time += 2
            line = ol
        }

        println(math.max(res, acc))
    }

    def other(line: Int) = (line + 1) % 2

  }

}


A permutation of length $$$n$$$ is an array consisting of $$$n$$$ distinct integers from $$$1$$$ to $$$n$$$ in arbitrary order. For example, $$$[2,3,1,5,4]$$$ is a permutation, but $$$[1,2,2]$$$ is not a permutation ($$$2$$$ appears twice in the array) and $$$[1,3,4]$$$ is also not a permutation ($$$n=3$$$ but there is $$$4$$$ in the array).For a positive integer $$$n$$$, we call a permutation $$$p$$$ of length $$$n$$$ good if the following condition holds for every pair $$$i$$$ and $$$j$$$ ($$$1 \le i \le j \le n$$$) —   $$$(p_i \text{ OR } p_{i+1} \text{ OR } \ldots \text{ OR } p_{j-1} \text{ OR } p_{j}) \ge j-i+1$$$, where $$$\text{OR}$$$ denotes the bitwise OR operation. In other words, a permutation $$$p$$$ is good if for every subarray of $$$p$$$, the $$$\text{OR}$$$ of all elements in it is not less than the number of elements in that subarray. Given a positive integer $$$n$$$, output any good permutation of length $$$n$$$. We can show that for the given constraints such a permutation always exists.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 100$$$). Description of the test cases follows. The first and only line of every test case contains a single integer $$$n$$$ ($$$1 \le n \le 100$$$).

For every test, output any good permutation of length $$$n$$$ on a separate line.

object A {
  import InOut._
  def main(args: Array[String]): Unit = {

    for (_ <- 1 to nextInt) {
      val n = nextInt
      out.println((1 to n).mkString(" "))
    }

    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _
    def nextToken: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new java.util.StringTokenizer(in.readLine)
      tokenizer.nextToken
    }
    def nextInt = Integer.parseInt(nextToken)
    def nextLong = java.lang.Long.parseLong(nextToken)
    def nextBig = BigInt(nextToken)
    def nextInts(n: Int) = Array.fill(n) { nextInt }
    def nextLongs(n: Int) = Array.fill(n) { nextLong }
    def nextBigs(n: Int) = Array.fill(n) { nextBig }
    def nextLine = in.readLine
  }
}

import scala.io.StdIn._

object A {

	def main(args: Array[String]) {
		val t = readInt()
		1 to t foreach { _ =>
			val n = readInt()
			for (i <- 1 to n) println(i)
		}
	}
}


You are given a weighted tree consisting of $$$n$$$ vertices. Recall that a tree is a connected graph without cycles. Vertices $$$u_i$$$ and $$$v_i$$$ are connected by an edge with weight $$$w_i$$$.You are given $$$m$$$ queries. The $$$i$$$-th query is given as an integer $$$q_i$$$. In this query you need to calculate the number of pairs of vertices $$$(u, v)$$$ ($$$u < v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n, m \le 2 \cdot 10^5$$$) — the number of vertices in the tree and the number of queries. Each of the next $$$n - 1$$$ lines describes an edge of the tree. Edge $$$i$$$ is denoted by three integers $$$u_i$$$, $$$v_i$$$ and $$$w_i$$$ — the labels of vertices it connects ($$$1 \le u_i, v_i \le n$$$, $$$u_i \ne v_i$$$) and the weight of the edge ($$$1 \le w_i \le 2 \cdot 10^5$$$). It is guaranteed that the given edges form a tree. The last line of the input contains $$$m$$$ integers $$$q_1, q_2, \dots, q_m$$$ ($$$1 \le q_i \le 2 \cdot 10^5$$$), where $$$q_i$$$ is the maximum weight of an edge in the $$$i$$$-th query.

Print $$$m$$$ integers — the answers to the queries. The $$$i$$$-th value should be equal to the number of pairs of vertices $$$(u, v)$$$ ($$$u < v$$$) such that the maximum weight of an edge on a simple path between $$$u$$$ and $$$v$$$ doesn't exceed $$$q_i$$$. Queries are numbered from $$$1$$$ to $$$m$$$ in the order of the input.

NoteThe picture shows the tree from the first example:

//package codeforces.contest1213

object PathQueries {

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
    val edgesList = (1 until n)
      .map { _ =>
        val Array(l, r, w) = io.StdIn.readLine.split(" ").map(_.toInt)
        (l min r, l max r, w)
      }
      .sortBy(_._3)
      .toList

    val parent = new Array[Int](n + 1)
    val setSize = new Array[Long](n + 1)

    def findParent(i: Int): Int =
      if (i == parent(i))
        i
      else {
        parent(i) = findParent(parent(i))
        parent(i)
      }

    (1 to n).foreach { i =>
      parent(i) = i
      setSize(i) = 1
    }

    @scala.annotation.tailrec
    def loop(edges: List[(Int, Int, Int)],
             max: Int,
             result: Long): (Long, List[(Int, Int, Int)]) =
      edges match {
        case ::(_ @(l, r, w), tl) if w <= max =>
          val lp = findParent(l)
          val rp = findParent(r)

          val newResult = result + setSize(lp) * setSize(rp)

          setSize(lp) += setSize(rp)
          parent(rp) = lp

          loop(tl, max, newResult)

        case _ => (result, edges)
      }

    val result = new Array[Long](m)

    io.StdIn.readLine
      .split(" ")
      .map(_.toInt)
      .zipWithIndex
      .sortBy(_._1)
      .foldLeft((0l, edgesList)) {
        case ((acc, ls), (q, i)) =>
          val (r, remaining) = loop(ls, q, acc)
          result(i) = r
          (r, remaining)
      }

    println(result.mkString(" "))
  }

}

//package codeforces.contest1213

object PathQueries {

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
    val edgesList = (1 until n)
      .map { _ =>
        val Array(l, r, w) = io.StdIn.readLine.split(" ").map(_.toInt)
        (l min r, l max r, w)
      }
      .sortBy(_._3)
      .toList

    val parent = new Array[Int](n + 1)
    val setSize = new Array[Int](n + 1)

    def findParent(i: Int): Int =
      if (i == parent(i))
        i
      else {
        parent(i) = findParent(i)
        parent(i)
      }

    (1 to n).foreach { i =>
      parent(i) = i
      setSize(i) = 1
    }

    @scala.annotation.tailrec
    def loop(edges: List[(Int, Int, Int)],
             max: Int,
             result: Int): (Int, List[(Int, Int, Int)]) =
      edges match {
        case ::(_ @(l, r, w), tl) if w <= max =>
          val lp = parent(l)
          val rp = parent(r)

          val newResult = result + setSize(lp) * setSize(rp)

          setSize(lp) += setSize(rp)
          parent(rp) = lp

          loop(tl, max, newResult)

        case _ => (result, edges)
      }

    val result = new Array[Int](m)

    io.StdIn.readLine
      .split(" ")
      .map(_.toInt)
      .zipWithIndex
      .sortBy(_._1)
      .foldLeft((0, edgesList)) {
        case ((acc, ls), (q, i)) =>
          val (r, remaining) = loop(ls, q, acc)
          result(i) = r
          (r, remaining)
      }

    println(result.mkString(" "))
  }

}

//package codeforces.contest1213

object PathQueries {

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
    val edgesList = (1 until n)
      .map { _ =>
        val Array(l, r, w) = io.StdIn.readLine.split(" ").map(_.toInt)
        (l min r, l max r, w)
      }
      .sortBy(_._3)
      .toList

    val parent = new Array[Int](n + 1)
    val setSize = new Array[Long](n + 1)

    def findParent(i: Int): Int =
      if (i == parent(i))
        i
      else {
        parent(i) = findParent(i)
        parent(i)
      }

    (1 to n).foreach { i =>
      parent(i) = i
      setSize(i) = 1
    }

    @scala.annotation.tailrec
    def loop(edges: List[(Int, Int, Int)],
             max: Int,
             result: Long): (Long, List[(Int, Int, Int)]) =
      edges match {
        case ::(_ @(l, r, w), tl) if w <= max =>
          val lp = parent(l)
          val rp = parent(r)

          val newResult = result + setSize(lp) * setSize(rp)

          setSize(lp) += setSize(rp)
          parent(rp) = lp

          loop(tl, max, newResult)

        case _ => (result, edges)
      }

    val result = new Array[Long](m)

    io.StdIn.readLine
      .split(" ")
      .map(_.toInt)
      .zipWithIndex
      .sortBy(_._1)
      .foldLeft((0l, edgesList)) {
        case ((acc, ls), (q, i)) =>
          val (r, remaining) = loop(ls, q, acc)
          result(i) = r
          (r, remaining)
      }

    println(result.mkString(" "))
  }

}

//package codeforces.contest1213

object PathQueries {

  def main(args: Array[String]): Unit = {
    val Array(n, m) = io.StdIn.readLine.split(" ").map(_.toInt)
    val edgesList = (1 until n)
      .map { _ =>
        val Array(l, r, w) = io.StdIn.readLine.split(" ").map(_.toInt)
        (l min r, l max r, w)
      }
      .sortBy(_._3)
      .toList

    val parent = new Array[Int](n + 1)
    val setSize = new Array[Int](n + 1)

    def findParent(i: Int): Int =
      if (i == parent(i))
        i
      else {
        parent(i) = findParent(i)
        parent(i)
      }

    (1 to n).foreach { i =>
      parent(i) = i
      setSize(i) = 1
    }

    @scala.annotation.tailrec
    def loop(edges: List[(Int, Int, Int)],
             max: Int,
             result: Int): (Int, List[(Int, Int, Int)]) =
      edges match {
        case ::(_ @(l, r, w), tl) if w <= max =>
          val lp = parent(l)
          val rp = parent(r)

          val newResult = result + setSize(lp) * setSize(rp)

          setSize(lp) += setSize(rp)
          parent(rp) = lp

          loop(tl, max, newResult)

        case _ => (result, edges)
      }

    val result = new Array[Long](m)

    io.StdIn.readLine
      .split(" ")
      .map(_.toInt)
      .zipWithIndex
      .sortBy(_._1)
      .foldLeft((0, edgesList)) {
        case ((acc, ls), (q, i)) =>
          val (r, remaining) = loop(ls, q, acc)
          result(i) = r
          (r, remaining)
      }

    println(result.mkString(" "))
  }

}


Palo Alto is an unusual city because it is an endless coordinate line. It is also known for the office of Lyft Level 5.Lyft has become so popular so that it is now used by all $$$m$$$ taxi drivers in the city, who every day transport the rest of the city residents — $$$n$$$ riders.Each resident (including taxi drivers) of Palo-Alto lives in its unique location (there is no such pair of residents that their coordinates are the same).The Lyft system is very clever: when a rider calls a taxi, his call does not go to all taxi drivers, but only to the one that is the closest to that person. If there are multiple ones with the same distance, then to taxi driver with a smaller coordinate is selected.But one morning the taxi drivers wondered: how many riders are there that would call the given taxi driver if they were the first to order a taxi on that day? In other words, you need to find for each taxi driver $$$i$$$ the number $$$a_{i}$$$ — the number of riders that would call the $$$i$$$-th taxi driver when all drivers and riders are at their home?The taxi driver can neither transport himself nor other taxi drivers.

The first line contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n,m \le 10^5$$$) — number of riders and taxi drivers. The second line contains $$$n + m$$$ integers $$$x_1, x_2, \ldots, x_{n+m}$$$ ($$$1 \le x_1 < x_2 < \ldots < x_{n+m} \le 10^9$$$), where $$$x_i$$$ is the coordinate where the $$$i$$$-th resident lives.  The third line contains $$$n + m$$$ integers $$$t_1, t_2, \ldots, t_{n+m}$$$ ($$$0 \le t_i \le 1$$$). If $$$t_i = 1$$$, then the $$$i$$$-th resident is a taxi driver, otherwise $$$t_i = 0$$$. It is guaranteed that the number of $$$i$$$ such that $$$t_i = 1$$$ is equal to $$$m$$$.

Print $$$m$$$ integers $$$a_1, a_2, \ldots, a_{m}$$$, where $$$a_i$$$ is the answer for the $$$i$$$-th taxi driver. The taxi driver has the number $$$i$$$ if among all the taxi drivers he lives in the $$$i$$$-th smallest coordinate (see examples for better understanding).

NoteIn the first example, we have only one taxi driver, which means an order from any of $$$n$$$ riders will go to him.In the second example, the first taxi driver lives at the point with the coordinate $$$2$$$, and the second one lives at the point with the coordinate $$$6$$$. Obviously, the nearest taxi driver to the rider who lives on the $$$3$$$ coordinate is the first one, and to the rider who lives on the coordinate $$$5$$$ is the second one. The rider who lives on the $$$4$$$ coordinate has the same distance to the first and the second taxi drivers, but since the first taxi driver has a smaller coordinate, the call from this rider will go to the first taxi driver.In the third example, we have one rider and the taxi driver nearest to him is the fourth one.

import java.util.Scanner

object Task2 {

  def main(args: Array[String]): Unit = {
    val scanner = new Scanner(System.in)
    val numberOfRiders = scanner.nextInt()
    val numberOfTaxiDrivers = scanner.nextInt()
    // Coordinates are always increasing and distinct
    val indexToCoordinates = new Array[Int](numberOfRiders + numberOfTaxiDrivers)
    indexToCoordinates.indices
      .foreach(i =>
        indexToCoordinates.update(i, scanner.nextInt())
      )
    val indexToIsTaxiDriver = new Array[Boolean](numberOfRiders + numberOfTaxiDrivers)
    indexToIsTaxiDriver.indices
      .foreach { i =>
        indexToIsTaxiDriver.update(i, scanner.nextInt() == 1)
      }
    val residentIndexToNearestTaxiDriverIndex = new Array[Int](numberOfRiders + numberOfTaxiDrivers)
    var currentTaxiDriverIndex = -1
    indexToCoordinates.indices
      .foreach { index =>
        if (indexToIsTaxiDriver(index)) {
          currentTaxiDriverIndex = index
        }
        residentIndexToNearestTaxiDriverIndex.update(index, currentTaxiDriverIndex)
      }
    // Now currentTaxiDriverIndex points to an existing taxi driver
    (indexToCoordinates.length - 1 to 0 by -1)
      .foreach { index =>
        if (indexToIsTaxiDriver(index)) {
          currentTaxiDriverIndex = index
        }
        val previousTaxiDriverDistance =
          if (residentIndexToNearestTaxiDriverIndex(index) == -1) {
            1000000001
          } else {
            Math.abs(indexToCoordinates(residentIndexToNearestTaxiDriverIndex(index)) - indexToCoordinates(index))
          }
        val currentTaxiDriverDistance =
          Math.abs(indexToCoordinates(currentTaxiDriverIndex) - indexToCoordinates(index))
        val nearestTaxiDriverIndex =
          if (previousTaxiDriverDistance <= currentTaxiDriverDistance) {
            residentIndexToNearestTaxiDriverIndex(index)
          } else {
            currentTaxiDriverIndex
          }
        residentIndexToNearestTaxiDriverIndex.update(index, nearestTaxiDriverIndex)
      }
    val taxiDriverIndexToNumberOfResidentWhoWouldCall = new Array[Int](numberOfRiders + numberOfTaxiDrivers)
    residentIndexToNearestTaxiDriverIndex.indices
      .foreach { index =>
        if (!indexToIsTaxiDriver(index)) {
          val driverIndex = residentIndexToNearestTaxiDriverIndex(index)
          taxiDriverIndexToNumberOfResidentWhoWouldCall.update(
            driverIndex,
            taxiDriverIndexToNumberOfResidentWhoWouldCall(driverIndex) + 1
          )
        }
      }
    val _taxiDriverIndexToNumberOfResidentWhoWouldCall = new Array[Int](numberOfTaxiDrivers)
    currentTaxiDriverIndex = 0
    taxiDriverIndexToNumberOfResidentWhoWouldCall.indices
      .foreach { index =>
        if (indexToIsTaxiDriver(index)) {
          _taxiDriverIndexToNumberOfResidentWhoWouldCall.update(currentTaxiDriverIndex, taxiDriverIndexToNumberOfResidentWhoWouldCall(index))
          currentTaxiDriverIndex += 1
        }
      }
    println(_taxiDriverIndexToNumberOfResidentWhoWouldCall.mkString(" "))
  }

}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, M = ni()
    val loc = na(N + M)
    var ri, di = 0
    val R = Array.ofDim[Int](N)
    val D = Array.ofDim[Int](M)
    rep(N + M) { i =>
      if (ni() == 1) {
        D(di) = loc(i)
        di += 1
      } else {
        R(ri) = loc(i)
        ri += 1
      }
    }

    val ans = Array.ofDim[Int](M)
    rep(M) { i =>
      def d1 = D(i) - D(i - 1)
      def d2 = D(i + 1) - D(i)
      def l = D(i) - (d1 - 1) / 2
      def r = D(i) + d2 / 2 // inclusive
      val lnum = if (i == 0) 0 else lowerBound(R, l)
      val rnum = if (i == M - 1) R.length else lowerBound(R, r + 1)
      val num = rnum - lnum
      ans(i) = num
    }

    out.println(ans.mkString(" "))
  }

  // あえてコピペ
  // 要はcountLt
  def lowerBound(a: Array[Int], x: Int): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
  def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
    val A1, A2 = Array.ofDim[Int](n)
    rep(n) { i =>
      A1(i) = ni() + offset
      A2(i) = ni() + offset
    }
    (A1, A2)
  }
  def nm(n: Int, m: Int): Array[Array[Int]] = {
    val A = Array.ofDim[Int](n, m)
    rep(n) { i =>
      rep(m) { j =>
        A(i)(j) = ni()
      }
    }
    A
  }
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }

  def cumSum(as: Array[Int]) = {
    val cum = Array.ofDim[Int](as.length + 1)
    rep(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import java.util

import scala.collection.mutable

object B extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, m) = readInts(2)
  val _xs = readInts(n + m)
  val isTaxi = readInts(n + m).map(_ == 1)

  val ts = Array.ofDim[Int](m)
  val xs = Array.ofDim[Int](n)

  var ti, xi = 0
  for {
    i <- _xs.indices
  } {
    if (isTaxi(i)) {
      ts(ti) = _xs(i)
      ti += 1
    } else {
      xs(xi) = _xs(i)
      xi += 1
    }
  }

  val as = Array.fill(m){ 0 }

  val tree = new util.TreeMap[Integer, Integer]()

  for (i <- ts.indices) tree.put(ts(i), i)

  for (x <- xs) {
    val left = tree.floorKey(x)
    val right = tree.ceilingKey(x)
    if (left == null) {
      as(tree.get(right)) += 1
    } else if (right == null) {
      as(tree.get(left)) += 1
    } else if (x - left <= right - x) {
      as(tree.get(left)) += 1
    } else {
      as(tree.get(right)) += 1
    }
  }

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(as.mkString(" "))

  Console.flush
}

import java.io._
import java.util.StringTokenizer

import scala.collection.mutable

object A extends App {

  def solve(in: InputReader): Unit = {
    val n, m = in.nextInt
    val arr = Array.fill(n + m)(in.nextInt)
    val b = Array.fill(n + m)(in.nextInt)
    val ans = Array.fill(m)(0)
    var i = 0
    var k = 0
    while (b(i) != 1) {
      i += 1
      ans(k) += 1
    }
    while (i < n + m) {
      var j = i + 1
      while (j < (n + m) && b(j) != 1) j += 1
      val distL = arr(i)
      val distR = if (j == (n + m)) 1e+15 else arr(j)
      (i + 1 until j).foreach { p =>
        if (arr(p) - distL <= distR - arr(p))
          ans(k) += 1
        else
          ans(k + 1) += 1
      }
      i = j
      k += 1
    }

    println(ans.mkString(" "))
  }

  solve(new InputReader(System.in))

  private class InputReader(val in: InputStream) {

    private val reader: BufferedReader = new BufferedReader(new InputStreamReader(in))
    private var tokenizer: StringTokenizer = _

    def nextInt: Int = {
      next.toInt
    }

    def nextDouble: Double = {
      next.toDouble
    }

    def nextLong: Long = {
      next.toLong
    }

    def next: String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens) {
        tokenizer = new StringTokenizer(readLine)
      }
      tokenizer.nextToken
    }

    def readLine: String = {
      try {
        reader.readLine()
      } catch {
        case e: IOException => throw new RuntimeException(e)
      }
    }
  }

}

object _1075B extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val n, m = io.read[Int]
    val pos = io.read[Vector, Int](n + m)
    val isDriver = io.read[Vector, Boolean](n + m)

    val left: IndexedSeq[Int] = pos.indices.scanLeft(Int.MaxValue) {
      case (nearestDriver, i) => if (isDriver(i)) pos(i) else nearestDriver
    }.tail

    val right: IndexedSeq[Int] = pos.indices.scanRight(Int.MaxValue) {
      case (i, nearestDriver) => if (isDriver(i)) pos(i) else nearestDriver
    }.init

    val ans: mutable.Map[Int, Int] = pos.indices
      .collect({case i if isDriver(i) => pos(i) -> 0})(collection.breakOut)

    for {
      i <- pos.indices if !isDriver(i)
      taxi = if ((left(i) - pos(i)).abs <= (right(i) - pos(i)).abs) left(i) else right(i)
    } ans(taxi) += 1

    io.writeAll(ans.toSeq.sorted.map(_._2))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

object _1075B extends CodeForcesApp {
  import annotation._, collection.{mutable, Searching}, util._, control._, math.Ordering.Implicits._, Searching._, Math._

  override def apply(io: IO): io.type = {
    val n, m = io.read[Int]
    val pos = io.read[Vector, Int](n + m)
    val isDriver = io.read[Vector, Boolean](n + m)
    val inf = 1e9.toInt

    val left: IndexedSeq[Int] = pos.indices.scanLeft(inf) {
      case (nearestDriver, i) => if (isDriver(i)) pos(i) else nearestDriver
    }.tail

    val right: IndexedSeq[Int] = pos.indices.scanRight(inf) {
      case (i, nearestDriver) => if (isDriver(i)) pos(i) else nearestDriver
    }.init

    val ans = mutable.Map.empty[Int, Int].withDefaultValue(0)

    pos.indices foreach {i =>
      if(isDriver(i)) {
        ans(pos(i)) = ans(pos(i)) max 0
      } else {
        val taxi = if ((left(i) - pos(i)).abs <= (right(i) - pos(i)).abs) left(i) else right(i)
        ans(taxi) += 1
      }
    }

    io.writeAll(ans.toSeq.sorted.map(_._2))
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

class IO(in: BufferedReader, out: BufferedWriter) extends Iterator[String] with AutoCloseable with Flushable {
  def this(reader: Reader, writer: Writer) = this(new BufferedReader(reader), new BufferedWriter(writer))
  def this(in: InputStream, out: OutputStream) = this(new InputStreamReader(in), new OutputStreamWriter(out))

  private[this] val tokenizers = Iterator.continually(in.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
  val printer = new PrintWriter(out, true)

  @inline private[this] def tokenizer() = {
    while(tokenizers.nonEmpty && !tokenizers.head.hasMoreTokens) tokenizers.next()
    tokenizers.headOption
  }

  def read[A](implicit read: IO.Read[A]): A = read.apply(this)
  def read[C[_], A: IO.Read](n: Int)(implicit b: CanBuild[A, C[A]]): C[A] = Iterator.fill(n)(read).to[C]

  def readTill(delim: String): String = tokenizer().get.nextToken(delim)
  def readTillEndOfLine(): String = readTill("\n\r")

  def readAll[A: IO.Read]: (Int, Vector[A]) = {
    val data = read[Vector[A]]
    (data.length, data)
  }

  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty

  def write(obj: Any): this.type = {
    printer.print(obj)
    this
  }
  def writeLine(): this.type = {
    printer.println()
    this
  }
  def writeLine(obj: Any): this.type = {
    printer.println(obj)
    this
  }
  def writeAll(obj: Traversable[Any], separator: String = " "): this.type = write(obj mkString separator)
  def query[A: IO.Read](question: Any): A = writeLine(question).read

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }

  object Read {
    implicit def collection[C[_], A: Read](implicit b: CanBuild[A, C[A]]) : Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                                   : Read[String]       = new Read(_.next())
    implicit val int                                                      : Read[Int]          = string.map(_.toInt)
    implicit val long                                                     : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                                   : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                                   : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                               : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                                 : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]                        : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]               : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                                  : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}


You are given a matrix of size $$$n \times n$$$ filled with lowercase English letters. You can change no more than $$$k$$$ letters in this matrix.Consider all paths from the upper left corner to the lower right corner that move from a cell to its neighboring cell to the right or down. Each path is associated with the string that is formed by all the letters in the cells the path visits. Thus, the length of each string is $$$2n - 1$$$.Find the lexicographically smallest string that can be associated with a path after changing letters in at most $$$k$$$ cells of the matrix.A string $$$a$$$ is lexicographically smaller than a string $$$b$$$, if the first different letter in $$$a$$$ and $$$b$$$ is smaller in $$$a$$$.

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le n \le 2000$$$, $$$0 \le k \le n^2$$$) — the size of the matrix and the number of letters you can change. Each of the next $$$n$$$ lines contains a string of $$$n$$$ lowercase English letters denoting one row of the matrix.

Output the lexicographically smallest string that can be associated with some valid path after changing no more than $$$k$$$ letters in the matrix.

7 6
ypnxnnp
pnxonpm
nxanpou
xnnpmud
nhtdudu
npmuduh
pmutsnz

NoteIn the first sample test case it is possible to change letters 'b' in cells $$$(2, 1)$$$ and $$$(3, 1)$$$ to 'a', then the minimum path contains cells $$$(1, 1), (2, 1), (3, 1), (4, 1), (4, 2), (4, 3), (4, 4)$$$. The first coordinate corresponds to the row and the second coordinate corresponds to the column.

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val grid = Array.ofDim[Array[Char]](N)
    rep(N) { i =>
      grid(i) = ns(N)
    }

    case class Coord(h: Int, w: Int)
    val INF = Int.MaxValue / 2

    def dijk_a(sh: Int, sw: Int) = {
      val d = Array.fill[Int](N, N)(INF)
      case class Visit(h: Int, w: Int, cost: Int)
      val queue = new java.util.ArrayDeque[Visit]()
      d(sh)(sw) = 0
      queue.add(Visit(sh, sw, 0))

      while(!queue.isEmpty) {
        val v = queue.poll()
        if (d(v.h)(v.w) == v.cost) {
          rep(2) { x =>
            val nh = v.h + (x ^ 1)
            val nw = v.w + x
            val c = if (grid(v.h)(v.w) == 'a') 0 else 1
            val next = v.cost + c
            if (nh < N && nw < N && K - next >= 0) {
              if (d(nh)(nw) > next) {
                d(nh)(nw) = next
                if (c == 0) {
                  queue.addFirst(Visit(nh, nw, next))
                } else {
                  queue.addLast(Visit(nh, nw, next))
                }
              }
            }
          }
        }
      }

      d
    }

    val d = dijk_a(0, 0)

    /**
      * 一番アルファベット順が小さいものだけを残す
      */
    class MinCharCoord {
      val coord = mutable.Set[Coord]()
      var char = 'z'

      def +=(a: Coord): Unit = {
        val c = grid(a.h)(a.w)
        if (c == char) {
          coord += a
        } else if (c < char) {
          char = c
          coord.clear()
          coord += a
        }
      }

      def clear(): Unit = {
        coord.clear()
        char = 'z'
      }

      def nonEmpty = coord.nonEmpty
      def head = coord.head
    }

    /**
      * aで埋めれる一番距離が大きくなる場所の次に行ける場所を返す
      * @return (aの個数, aの次の候補)
      */
    def findMaxDist(): (Int, MinCharCoord) = {
      // 右下までaで埋めれた場合
      if (d(N - 1)(N - 1) != INF && (d(N - 1)(N - 1) < K || grid(N - 1)(N - 1) == 'a')) {
        (2 * N - 1, new MinCharCoord)
      } else {
        var dist = 0
        val coord = new MinCharCoord
        rep(N) { h =>
          rep(N) { w =>
            if (d(h)(w) != INF) {
              val move = h + w

              if (dist == move) {
                coord += Coord(h, w)
              } else if (dist < move) {
                dist = move
                coord.clear()
                coord += Coord(h, w)
              }
            }
          }
        }
        (dist, coord)
      }
    }

    val (as, ini) = findMaxDist()

    val str = new mutable.StringBuilder()
    rep(as)(_ => str += 'a')

    var q = ini
    var next = new MinCharCoord

    // 深さでBFSする感じ
    while (q.nonEmpty) {
      str += q.char
      q.coord foreach { c =>
        rep(2) { x =>
          val nh = c.h + (x ^ 1)
          val nw = c.w + x
          if (nh < N && nw < N) next += Coord(nh, nw)
        }
      }
      val temp = q
      q = next
      next = temp
      next.clear()
    }

    out.println(str.toString)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(n, k) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }

  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k

  for (step <- 0 until 2 * n - 1) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (ks(i)(j) > 0 && cs(i)(j) != 'a') {
        cs(i)(j) = 'a'
        ks(i)(j) -= 1
      }
      if (j < n - 1) {
        ks(i)(j + 1) = Math.max(ks(i)(j + 1), ks(i)(j))
      }
      if (i < n - 1) {
        ks(i + 1)(j) = Math.max(ks(i + 1)(j), ks(i)(j))
      }
      i += 1
      j -= 1
    }
  }

  val best = Array.fill(2 * n - 1){ 'z' }
  val canReach = Array.fill(n, n){ false }

  canReach(0)(0) = true

  for (step <- 0 until 2 * n - 1) {

    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      val c = cs(i)(j)
      if (canReach(i)(j) && c <= best(step)) best(step) = c
      i += 1
      j -= 1
    }

    i = if (step < n) 0 else step - n + 1
    j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      val c = cs(i)(j)
      if (canReach(i)(j) && c <= best(step)) {
        if (j < n - 1) canReach(i)(j + 1) = true
        if (i < n - 1) canReach(i + 1)(j) = true
      }
      i += 1
      j -= 1
    }
  }

  println(best.mkString)
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val grid = Array.ofDim[Array[Char]](N)
    rep(N) { i =>
      grid(i) = ns(N)
    }

    case class Coord(h: Int, w: Int)
    val INF = Int.MaxValue / 2

    def dijk_a(sh: Int, sw: Int) = {
      val d = Array.fill[Int](N, N)(INF)
      case class Visit(h: Int, w: Int, cost: Int)
      val queue = new java.util.ArrayDeque[Visit]()
      d(sh)(sw) = 0
      queue.add(Visit(sh, sw, 0))

      while(!queue.isEmpty) {
        val v = queue.poll()
        if (d(v.h)(v.w) == v.cost) {
          rep(2) { x =>
            val nh = v.h + (x ^ 1)
            val nw = v.w + x
            val c = if (grid(v.h)(v.w) == 'a') 0 else 1
            val next = v.cost + c
            if (nh < N && nw < N && K - next >= 0) {
              if (d(nh)(nw) > next) {
                d(nh)(nw) = next
                if (c == 0) {
                  queue.addFirst(Visit(nh, nw, next))
                } else {
                  queue.addLast(Visit(nh, nw, next))
                }
              }
            }
          }
        }
      }

      d
    }

    val d = dijk_a(0, 0)

    /**
      * 一番アルファベット順が小さいものだけを残す
      */
    class MinCharCoord {
      val coord = mutable.Set[Coord]()
      var char = 'z'

      def +=(a: Coord): Unit = {
        val c = grid(a.h)(a.w)
        if (c == char) {
          coord += a
        } else if (c < char) {
          char = c
          coord.clear()
          coord += a
        }
      }

      def clear(): Unit = {
        coord.clear()
        char = 'z'
      }

      def nonEmpty = coord.nonEmpty
      def head = coord.head
    }

    /**
      * aで埋めれる一番距離が大きくなる場所の次に行ける場所を返す
      * @return (aの個数, aの次の候補)
      */
    def findMaxDist(): (Int, MinCharCoord) = {
      // 右下までaで埋めれた場合
      if (d(N - 1)(N - 1) != INF && (d(N - 1)(N - 1) > 0 || grid(N - 1)(N - 1) == 'a')) {
        (2 * N - 1, new MinCharCoord)
      } else {
        var dist = 0
        val coord = new MinCharCoord
        rep(N) { h =>
          rep(N) { w =>
            if (d(h)(w) != INF) {
              val move = h + w

              if (dist == move) {
                coord += Coord(h, w)
              } else if (dist < move) {
                dist = move
                coord.clear()
                coord += Coord(h, w)
              }
            }
          }
        }
        (dist, coord)
      }
    }

    val (as, ini) = findMaxDist()

    val str = new mutable.StringBuilder()
    rep(as)(_ => str += 'a')

    var q = ini
    var next = new MinCharCoord

    // 深さでBFSする感じ
    while (q.nonEmpty) {
      str += q.char
      q.coord foreach { c =>
        rep(2) { x =>
          val nh = c.h + (x ^ 1)
          val nw = c.w + x
          if (nh < N && nw < N) next += Coord(nh, nw)
        }
      }
      val temp = q
      q = next
      next = temp
      next.clear()
    }

    out.println(str.toString)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object Main {
  def main(args: Array[String]): Unit = {
    val s = new Main()
    s.solve()
    s.out.flush()
  }
}

class Main {
  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.util.Sorting
  import math.{abs, max, min}
  import mutable.{ArrayBuffer, ListBuffer}
  import scala.reflect.ClassTag

  val MOD = 1000000007
  val out = new PrintWriter(System.out)

  def solve(): Unit = {
    val N, K = ni()
    val grid = Array.ofDim[Array[Char]](N)
    rep(N) { i =>
      grid(i) = ns(N)
    }

    case class Coord(h: Int, w: Int)
    val INF = Int.MaxValue / 2

    def dijk_a(sh: Int, sw: Int) = {
      val d = Array.fill[Int](N, N)(INF)
      case class Visit(h: Int, w: Int, cost: Int)
      val queue = new java.util.ArrayDeque[Visit]()
      d(sh)(sw) = 0
      queue.add(Visit(sh, sw, 0))

      while(!queue.isEmpty) {
        val v = queue.poll()
        if (d(v.h)(v.w) == v.cost) {
          rep(2) { x =>
            val nh = v.h + (x ^ 1)
            val nw = v.w + x
            val c = if (grid(v.h)(v.w) == 'a') 0 else 1
            val next = v.cost + c
            if (nh < N && nw < N && K - next >= 0) {
              if (d(nh)(nw) > next) {
                d(nh)(nw) = next
                if (c == 0) {
                  queue.addFirst(Visit(nh, nw, next))
                } else {
                  queue.addLast(Visit(nh, nw, next))
                }
              }
            }
          }
        }
      }

      d
    }

    val d = dijk_a(0, 0)
    def findMaxDist(): (Int, ArrayBuffer[Coord]) = {
      var dist = 0
      val coord = ArrayBuffer[Coord]()
      rep(N) { h =>
        rep(N) { w =>
          if (d(h)(w) != INF) {
            if (dist == h + w) {
              coord += Coord(h, w)
            } else if (dist < h + w) {
              dist = h + w
              coord.clear()
              coord += Coord(h, w)
            }
          }
        }
      }
      (dist, coord)
    }

    def filterMinAlpha(as: mutable.Set[Coord]): mutable.Set[Coord] = {
      as.groupBy(c => grid(c.h)(c.w)).toSeq.minBy(_._1)._2
    }

    val (as, ini) = findMaxDist()

    val str = new mutable.StringBuilder()
    var q = mutable.Set(ini: _*)
    rep(as)(_ => str += 'a')

    // 深さでBFSする感じ
    while (q.nonEmpty) {
      val next = mutable.Set[Coord]()
      val filtered = filterMinAlpha(q)
      val a = filtered.head
      str += grid(a.h)(a.w)
      filtered foreach { c =>
        rep(2) { x =>
          val nh = c.h + (x ^ 1)
          val nw = c.w + x
          if (nh < N && nw < N) next += Coord(nh, nw)
        }
      }
      q = next
    }

    out.println(str.toString)
  }

  class InputReader(val stream: InputStream) {
    private val reader = new BufferedReader(new InputStreamReader(stream), 32768)
    private var tokenizer: StringTokenizer = _

    def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = next().toInt
    def nextLong(): Long = next().toLong
    def nextChar(): Char = next().charAt(0)
  }
  val sc = new InputReader(System.in)
  def ni(): Int = sc.nextInt()
  def nl(): Long = sc.nextLong()
  def nc(): Char = sc.nextChar()
  def ns(): String = sc.next()
  def ns(n: Int): Array[Char] = ns().toCharArray
  def na(n: Int): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  def rep(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def rep_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }

  def map[@specialized A: ClassTag](n: Int)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

  def sumL(as: Array[Int]): Long = {
    var s = 0L
    rep(as.length)(i => s += as(i))
    s
  }
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, k) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }

  val best = Array.fill(2 * n - 1){ 'z' }

  best(0) = cs(0)(0)
  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k

  for (step <- 0 until 2 * n - 2) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (ks(i)(j) > 0) best(step) = 'a'
      val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)
      if (c <= best(step)) {
        val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1
        if (j < n - 1) {
          if (cs(i)(j + 1) <= best(step + 1)) {
            best(step + 1) = cs(i)(j + 1)
          }
          ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)
        }
        if (i < n - 1) {
          if (cs(i + 1)(j) <= best(step + 1)) {
            best(step + 1) = cs(i + 1)(j)
          }
          ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)
        }
      }
      i += 1
      j -= 1
    }
  }

  if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(best.mkString)

  Console.flush
}

import scala.collection.mutable

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, k0) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }
  var k = k0

  if (cs(0)(0) != 'a' && k > 0) {
    cs(0)(0) = 'a'
    k -= 1
  }

  val best = Array.fill(2 * n - 1){ 'z' }

  best(0) = cs(0)(0)
  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k

  for (step <- 0 until 2 * n - 2) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (ks(i)(j) > 0) best(step) = 'a'
      val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)
      if (c <= best(step)) {
        val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1
        if (j < n - 1 && cs(i)(j + 1) <= best(step + 1)) {
          best(step + 1) = cs(i)(j + 1)
          ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)
        }
        if (i < n - 1 && cs(i + 1)(j) <= best(step + 1)) {
          best(step + 1) = cs(i + 1)(j)
          ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)
        }
      }
      i += 1
      j -= 1
    }
  }

  if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(best.mkString)

  Console.flush
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(n, k) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }

  val best = Array.fill(2 * n - 1){ 'z' }
  val canReach = Array.fill(n, n){ false }

  best(0) = cs(0)(0)
  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k
  canReach(0)(0) = true

  for (step <- 0 until 2 * n - 2) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (ks(i)(j) > 0) best(step) = 'a'
      else if (cs(i)(j) < best(step)) best(step) = cs(i)(j)
      i += 1
      j -= 1
    }
    i = if (step < n) 0 else step - n + 1
    j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)
      if (canReach(i)(j) && c <= best(step)) {
        val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1
        if (j < n - 1) {
          if (cs(i)(j + 1) <= best(step + 1)) {
            best(step + 1) = cs(i)(j + 1)
            canReach(i)(j + 1) = true
          }
          ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)
        }
        if (i < n - 1) {
          if (cs(i + 1)(j) <= best(step + 1)) {
            best(step + 1) = cs(i + 1)(j)
            canReach(i + 1)(j) = true
          }
          ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)
        }
      }
      i += 1
      j -= 1
    }
  }

  if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'

  println(best.mkString)
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(n, k) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }

  val best = Array.fill(2 * n - 1){ 'z' }
  val canReach = Array.fill(n, n){ false }

  best(0) = cs(0)(0)
  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k
  canReach(0)(0) = true

  for (step <- 0 until 2 * n - 2) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (ks(i)(j) > 0) best(step) = 'a'
      i += 1
      j -= 1
    }
    i = if (step < n) 0 else step - n + 1
    j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)
      if (canReach(i)(j) && c <= best(step)) {
        val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1
        if (j < n - 1) {
          if (cs(i)(j + 1) <= best(step + 1)) {
            best(step + 1) = cs(i)(j + 1)
            canReach(i)(j + 1) = true
          }
          ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)
        }
        if (i < n - 1) {
          if (cs(i + 1)(j) <= best(step + 1)) {
            best(step + 1) = cs(i + 1)(j)
            canReach(i + 1)(j) = true
          }
          ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)
        }
      }
      i += 1
      j -= 1
    }
  }

  if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'

  println(best.mkString)
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }

  val Array(n, k) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }

  val best = Array.fill(2 * n - 1){ 'z' }
  val canReach = Array.fill(n, n){ false }

  best(0) = cs(0)(0)
  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k
  canReach(0)(0) = true

  for (step <- 0 until 2 * n - 2) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (canReach(i)(j)) {
        if (ks(i)(j) > 0) best(step) = 'a'
        else if (cs(i)(j) < best(step)) best(step) = cs(i)(j)
      }
      i += 1
      j -= 1
    }
    i = if (step < n) 0 else step - n + 1
    j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)
      if (canReach(i)(j) && c <= best(step)) {
        val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1
        if (j < n - 1) {
          if (cs(i)(j + 1) <= best(step + 1)) {
            best(step + 1) = cs(i)(j + 1)
            canReach(i)(j + 1) = true
          }
          ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)
        }
        if (i < n - 1) {
          if (cs(i + 1)(j) <= best(step + 1)) {
            best(step + 1) = cs(i + 1)(j)
            canReach(i + 1)(j) = true
          }
          ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)
        }
      }
      i += 1
      j -= 1
    }
  }

  if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'

  println(best.mkString)
}

object D extends App {

  @inline def tokenizeLine = new java.util.StringTokenizer(readLine)
  def readInts(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt) }
  def readLongs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong) }
  def readBigs(n: Int) = { val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken)) }

  val Array(n, k) = readInts(2)
  val cs = Array.fill(n){ readLine.toCharArray }

  val best = Array.fill(2 * n - 1){ 'z' }

  best(0) = cs(0)(0)
  val ks = Array.fill(n, n)(0)
  ks(0)(0) = k

  for (step <- 0 until 2 * n - 2) {
    var i = if (step < n) 0 else step - n + 1
    var j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      if (ks(i)(j) > 0) best(step) = 'a'
      i += 1
      j -= 1
    }
    i = if (step < n) 0 else step - n + 1
    j = if (step < n) step else n - 1
    while (j >= 0 && i < n) {
      val c = if (ks(i)(j) > 0) 'a' else cs(i)(j)
      if (c <= best(step)) {
        val kk = if (cs(i)(j) == 'a') ks(i)(j) else ks(i)(j) - 1
        if (j < n - 1) {
          if (cs(i)(j + 1) <= best(step + 1)) {
            best(step + 1) = cs(i)(j + 1)
          }
          ks(i)(j + 1) = Math.max(ks(i)(j + 1), kk)
        }
        if (i < n - 1) {
          if (cs(i + 1)(j) <= best(step + 1)) {
            best(step + 1) = cs(i + 1)(j)
          }
          ks(i + 1)(j) = Math.max(ks(i + 1)(j), kk)
        }
      }
      i += 1
      j -= 1
    }
  }

  if (ks(n - 1)(n - 1) > 0) best(2 * n - 2) = 'a'

  Console.setOut(new java.io.BufferedOutputStream(Console.out))

  println(best.mkString)

  Console.flush
}


Phoenix loves beautiful arrays. An array is beautiful if all its subarrays of length $$$k$$$ have the same sum. A subarray of an array is any sequence of consecutive elements.Phoenix currently has an array $$$a$$$ of length $$$n$$$. He wants to insert some number of integers, possibly zero, into his array such that it becomes beautiful. The inserted integers must be between $$$1$$$ and $$$n$$$ inclusive. Integers may be inserted anywhere (even before the first or after the last element), and he is not trying to minimize the number of inserted integers.

The input consists of multiple test cases. The first line contains an integer $$$t$$$ ($$$1 \le t \le 50$$$) — the number of test cases. The first line of each test case contains two integers $$$n$$$ and $$$k$$$ ($$$1 \le k \le n \le 100$$$). The second line of each test case contains $$$n$$$ space-separated integers ($$$1 \le a_i \le n$$$) — the array that Phoenix currently has. This array may or may not be already beautiful.

For each test case, if it is impossible to create a beautiful array, print -1. Otherwise, print two lines. The first line should contain the length of the beautiful array $$$m$$$ ($$$n \le m \le 10^4$$$). You don't need to minimize $$$m$$$. The second line should contain $$$m$$$ space-separated integers ($$$1 \le b_i \le n$$$) — a beautiful array that Phoenix can obtain after inserting some, possibly zero, integers into his array $$$a$$$. You may print integers that weren't originally in array $$$a$$$. If there are multiple solutions, print any. It's guaranteed that if we can make array $$$a$$$ beautiful, we can always make it with resulting length no more than $$$10^4$$$.

NoteIn the first test case, we can make array $$$a$$$ beautiful by inserting the integer $$$1$$$ at index $$$3$$$ (in between the two existing $$$2$$$s). Now, all subarrays of length $$$k=2$$$ have the same sum $$$3$$$. There exists many other possible solutions, for example:   $$$2, 1, 2, 1, 2, 1$$$  $$$1, 2, 1, 2, 1, 2$$$ In the second test case, the array is already beautiful: all subarrays of length $$$k=3$$$ have the same sum $$$5$$$.In the third test case, it can be shown that we cannot insert numbers to make array $$$a$$$ beautiful.In the fourth test case, the array $$$b$$$ shown is beautiful and all subarrays of length $$$k=4$$$ have the same sum $$$10$$$. There exist other solutions also.

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ad = an.distinct.toList
    val d  = ad.length

    if (d > k) println(-1)
    else {
      val sub                    = ad ::: (1 to k).toList.diff(ad).take(k - d)
      lazy val subs: Stream[Int] = sub.toStream #::: subs

      val ans = subs.take(k * n).toList

      println(ans.length)
      println(ans.mkString(" "))
    }
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ad = an.distinct.toList

    val ans =
      if (ad.length > k) List()
      else {
        val sub = ad ::: (1 to n).toList.diff(ad).take(k - ad.length)

        lazy val subs: Stream[Int] = sub.toStream #::: subs

        subs.take(k * an.length).toList
      }

    if (ans.isEmpty) println(-1)
    else {
      println(ans.length)
      println(ans.mkString(" "))
    }
  }
}

object Main {

  import java.io._
  import java.util.StringTokenizer

  import scala.collection.mutable
  import scala.collection.mutable.ListBuffer
  def main(args: Array[String]): Unit = {
    solve(System.in,System.out)
  }
  def solve(inputStream: InputStream, out: PrintStream): Unit = {
    val in = new InputReader(inputStream)
    val numCases = in.nextInt()
    (1 to numCases).foreach{ _ =>
      val (n,k) = (in.nextInt(),in.nextInt())

      val a = (1 to n).map(_ => in.nextInt()).distinct.toArray
      if(a.length > k){
        out.println(-1)
      }else{
        out.println(10000)
        var i = 0
        var e = 0
        val b = a ++ (Array.fill(k-a.length)(1))
        val sb = new mutable.StringBuilder()
        while(e<10000){
          sb.append(b(i))
          if(e < 10000-1)
            sb.append(' ')
          i += 1
          if(i >= k)
            i = 0
          e += 1
        }
        out.println(sb.toString())

      }

    }
  }
  class InputReader(stream: InputStream){
    val reader: BufferedReader = new BufferedReader(new InputStreamReader(stream),32768)
    var tokenizer: StringTokenizer = _
    def next(): String = {
      while(tokenizer == null || !tokenizer.hasMoreTokens){
        try{
          tokenizer = new StringTokenizer(reader.readLine())
        }catch {
          case e: IOException => throw new RuntimeException(e)
        }
      }
      tokenizer.nextToken()
    }
    def nextInt(): Int =  next().toInt
    def nextLong(): Long =  next().toLong
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    lazy val ak: Stream[Int] = (1 to k).toStream #::: ak

    val am =
      if (an.max > k) List()
      else ak.take(k * an.length).toList

    if (am.isEmpty) println(-1)
    else {
      println(am.length)
      println(am.mkString(" "))
    }
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val amin = an.min
    val amax = an.max

    val t = amax - amin + 1

    val ans =
      if (t > k) List()
      else {
        val r = n.min(amax + k - t)
        val l = r - k + 1

        if (l <= 0) List()
        else {
          lazy val ak: Stream[Int] = (l to r).toStream #::: ak

          ak.take(k * an.length).toList
        }
      }

    if (ans.isEmpty) println(-1)
    else {
      println(ans.length)
      println(ans.mkString(" "))
    }
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val amin = an.min
    val amax = an.max

    lazy val ak: Stream[Int] = (amin to (amin + k - 1)).toStream #::: ak

    val ans =
      if (amax - amin + 1 > k) List()
      else ak.take(k * an.length).toList

    if (ans.isEmpty) println(-1)
    else {
      println(ans.length)
      println(ans.mkString(" "))
    }
  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ad = an.distinct.toList
    val d  = ad.length

    if (d > k) println(-1)
    else {
      val sub                    = ad ::: ad.diff(1 to n).take(k - d)
      lazy val subs: Stream[Int] = sub.toStream #::: subs

      val ans = subs.take(k * n).toList

      println(ans.length)
      println(ans.mkString(" "))
    }

  }
}

object B extends App {
  val t = scala.io.StdIn.readInt()

  (0 until t).foreach { _ =>
    val Array(n, k) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
    val an          = scala.io.StdIn.readLine().split(" ").map(_.toInt)

    val ad = an.distinct.toList
    val d  = ad.length

    if (d > k) println(-1)
    else {
      val sub                    = ad ::: (1 to k).toList.diff(ad)
      lazy val subs: Stream[Int] = sub.toStream #::: subs

      val ans = subs.take(k * n).toList

      println(ans.length)
      println(ans.mkString(" "))
    }
  }
}