Two players, Red and Blue, are at it again, and this time they're playing with crayons! The mischievous duo is now vandalizing a rooted tree, by coloring the nodes while playing their favorite game.The game works as follows: there is a tree of size $$$n$$$, rooted at node $$$1$$$, where each node is initially white. Red and Blue get one turn each. Red goes first. In Red's turn, he can do the following operation any number of times:   Pick any subtree of the rooted tree, and color every node in the subtree red.  However, to make the game fair, Red is only allowed to color $$$k$$$ nodes of the tree. In other words, after Red's turn, at most $$$k$$$ of the nodes can be colored red.Then, it's Blue's turn. Blue can do the following operation any number of times:   Pick any subtree of the rooted tree, and color every node in the subtree blue. However, he's not allowed to choose a subtree that contains a node already colored red, as that would make the node purple and no one likes purple crayon.  Note: there's no restriction on the number of nodes Blue can color, as long as he doesn't color a node that Red has already colored.After the two turns, the score of the game is determined as follows: let $$$w$$$ be the number of white nodes, $$$r$$$ be the number of red nodes, and $$$b$$$ be the number of blue nodes. The score of the game is $$$w \cdot (r - b)$$$.Red wants to maximize this score, and Blue wants to minimize it. If both players play optimally, what will the final score of the game be?

The first line contains two integers $$$n$$$ and $$$k$$$ ($$$2 \le n \le 2 \cdot 10^5$$$; $$$1 \le k \le n$$$) — the number of vertices in the tree and the maximum number of red nodes. Next $$$n - 1$$$ lines contains description of edges. The $$$i$$$-th line contains two space separated integers $$$u_i$$$ and $$$v_i$$$ ($$$1 \le u_i, v_i \le n$$$; $$$u_i \neq v_i$$$) — the $$$i$$$-th edge of the tree. It's guaranteed that given edges form a tree.

Print one integer — the resulting score if both Red and Blue play optimally.

NoteIn the first test case, the optimal strategy is as follows:   Red chooses to color the subtrees of nodes $$$2$$$ and $$$3$$$.  Blue chooses to color the subtree of node $$$4$$$.  At the end of this process, nodes $$$2$$$ and $$$3$$$ are red, node $$$4$$$ is blue, and node $$$1$$$ is white. The score of the game is $$$1 \cdot (2 - 1) = 1$$$.In the second test case, the optimal strategy is as follows:   Red chooses to color the subtree of node $$$4$$$. This colors both nodes $$$4$$$ and $$$5$$$.  Blue does not have any options, so nothing is colored blue.  At the end of this process, nodes $$$4$$$ and $$$5$$$ are red, and nodes $$$1$$$, $$$2$$$ and $$$3$$$ are white. The score of the game is $$$3 \cdot (2 - 0) = 6$$$.For the third test case:  The score of the game is $$$4 \cdot (2 - 1) = 4$$$.

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = b.cost - a.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed).toLong
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == {
            1 + {
              par.parentOpt match {
                case None => 0
                case _ => 1
              }
            }
          }
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = {
      if (rem <= numR) {
        rem
      } else {
        rem.min(N/2)
      }
    }
    val ans: Long = (N - (numB + numR)).toLong * (numR - numB).toLong
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed).toLong
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == {
            1 + {
              par.parentOpt match {
                case None => 0
                case _ => 1
              }
            }
          }
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = {
      if (rem <= numR) {
        rem
      } else {
        rem.min(N/2)
      }
    }
    val ans: Long = (N - (numB + numR)).toLong * (numR - numB).toLong
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = {
      if (rem <= numR) {
        rem
      } else {
        rem.min(((rem - numR + numW) / 2) + numR)
      }
    }
    val ans: Long = (N - (numB + numR)).toLong * (numR - numB).toLong
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = {
      if (rem <= numR) {
        rem
      } else {
        rem.min(((rem - numR + numW) / 2) + numR)
      }
    }
    val ans: Long = numW.toLong * (numR - numB).toLong
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = {
      if (rem <= numR) {
        rem
      } else {
        rem.min(((rem - numR + numW) / 2) + numR)
      }
    }
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = {
      if (rem <= numR) {
        rem
      } else {
        rem.min((rem - numR + numW) / 2) + numR
      }
    }
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val rem = (N - (numW + numR))
    val numB = rem.min((rem + numW) / 2)
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = b.cost - a.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val numB = N - (numW + numR)
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = false
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}
import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = b.cost - a.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val numB = N - (numW + numR)
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.isEmpty || cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isDefined)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val numB = N - (numW + numR)
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}

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

import scala.math.max
import scala.math.min
import scala.reflect.ClassTag
import scala.collection.immutable._

object Main {
  def main(args: Array[String]): Unit = {
    try {
      val (in, out) =
        if (isOnlineJudge) {
          (
            new FastScanner(new InputStreamReader(System.in)),
            new PrintWriter(System.out)
          )
        } else {
          (
            new FastScanner(new FileReader(new File("/home/naman/Desktop/Ramdom/CP/scala/src/input.txt"))),
            new PrintWriter(new File("/home/naman/Desktop/Ramdom/CP/scala/src/output.txt"))
          )
        }
      new CF1615E(in, out).solve()
      out.flush()
      out.close()
    } catch {
      case e: IOException => e.printStackTrace()
    }
  }

  private[this] val isOnlineJudge = true
  class FastScanner(val streamReader: InputStreamReader) {
    private[this] val reader = new BufferedReader(streamReader, 32768)
    private[this] var tokenizer: StringTokenizer = _

    @inline private[this] final def next(): String = {
      while (tokenizer == null || !tokenizer.hasMoreTokens)
        tokenizer = new StringTokenizer(reader.readLine)
      tokenizer.nextToken
    }

    def nextInt(): Int = Integer.parseInt(next())

    def nextLong(): Long = java.lang.Long.parseLong(next())

    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()

    def nl(): Long = nextLong()

    def nc(): Char = nextChar()

    def ns(): String = 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 TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }

  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]): Array[Long] = {
    val cum = Array.ofDim[Long](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

import scala.collection.mutable
import scala.collection.mutable.{ArrayBuffer, ListBuffer}

object Node {
  implicit object ord extends Ordering[Node] {
    def compare(a: Node, b: Node): Int = a.cost - b.cost
  }
}

class Node{
  var parentOpt: Option[Node] = None
  var cost = 1
  val neighbours: ListBuffer[Node] = ListBuffer.empty
  var removed = 0
}

class CF1615E(fScanner: Main.FastScanner, out: java.io.PrintWriter) {
  import Main._
  import fScanner._

  def dfs(cur: Node): Unit = {
    cur.neighbours.foreach{ nbr =>
      if (cur.parentOpt.exists(nbr != _)) {
        nbr.parentOpt = Some(cur)
        dfs(nbr)
      }
    }
  }

  def solve(): Unit = {
    val N = ni()
    val K = ni()

    val nodes: ArrayBuffer[Node] = ArrayBuffer.empty
    nodes += new Node

    (1 to N).foreach{ _ =>
      nodes += new Node
    }

    (1 until N).foreach{ _ =>
      val u = ni()
      val v = ni()
      nodes(u).neighbours.append(nodes(v))
      nodes(v).neighbours.append(nodes(u))
    }

    dfs(nodes(1))

    val initialLeafs =
      nodes.filter(node => node.neighbours.size == 1 && node.parentOpt.isEmpty)
    val numL = initialLeafs.size
//    println(s"numL : ${numL}")
    if (numL <= K) {
      val numRed = K.min(numL.max(N/2))
      val ans: Long = numRed.toLong * (N - numRed)
      out.println(ans)
      return
    }

    val pq: mutable.PriorityQueue[Node] = mutable.PriorityQueue[Node](initialLeafs: _*)

    var numR = numL
    var numW = N - numR

    while(numR > K && pq.nonEmpty) {
      val node = pq.dequeue()
      if (
        node.parentOpt.exists{ par =>
          (par.neighbours.size - par.removed) == 1
        }
      ) {
        node.parentOpt.foreach{ par =>
          par.cost = node.cost + 1
          pq.enqueue(par)
        }
      }
      else {
        node.parentOpt.foreach(_.removed += 1)
        numR -= 1
        numW -= (node.cost - 1)
      }
    }

    val numB = N - (numW + numR)
    val ans: Long = numW.toLong * (numR - numB)
    out.println(ans)
  }
}


AquaMoon and Cirno are playing an interesting game with arrays. Cirno has prepared two arrays $$$a$$$ and $$$b$$$, both consist of $$$n$$$ non-negative integers. AquaMoon can perform the following operation an arbitrary number of times (possibly zero):  She chooses two indices $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n$$$), then decreases the $$$i$$$-th element of array $$$a$$$ by $$$1$$$, and increases the $$$j$$$-th element of array $$$a$$$ by $$$1$$$. The resulting values at $$$i$$$-th and $$$j$$$-th index of array $$$a$$$ are $$$a_i - 1$$$ and $$$a_j + 1$$$, respectively. Each element of array $$$a$$$ must be non-negative after each operation. If $$$i = j$$$ this operation doesn't change the array $$$a$$$. AquaMoon wants to make some operations to make arrays $$$a$$$ and $$$b$$$ equal. Two arrays $$$a$$$ and $$$b$$$ are considered equal if and only if $$$a_i = b_i$$$ for all $$$1 \leq i \leq n$$$.Help AquaMoon to find a sequence of operations that will solve her problem or find, that it is impossible to make arrays $$$a$$$ and $$$b$$$ equal.Please note, that you don't have to minimize the number of operations.

The input consists of multiple test cases. The first line contains a single integer $$$t$$$ ($$$1 \leq t \leq 100$$$) — the number of test cases. The first line of each test case contains a single integer $$$n$$$ ($$$1 \leq n \leq 100$$$). The second line of each test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$0 \leq a_i \leq 100$$$). The sum of all $$$a_i$$$ does not exceed $$$100$$$. The third line of each test case contains $$$n$$$ integers $$$b_1, b_2, \dots, b_n$$$ ($$$0 \leq b_i \leq 100$$$). The sum of all $$$b_i$$$ does not exceed $$$100$$$.

For each test case print "-1" on the only line if it is impossible to make two arrays equal with some sequence of operations. Otherwise, print an integer $$$m$$$ ($$$0 \leq m \leq 100$$$) in the first line — the number of operations. Then print $$$m$$$ lines, each line consists of two integers $$$i$$$ and $$$j$$$ — the indices you choose for the operation. It can be proven that if it is possible to make two arrays equal with some sequence of operations, there exists a sequence with $$$m \leq 100$$$. If there are multiple possible solutions, you can print any.

NoteIn the first example, we do the following operations:  $$$i = 2$$$, $$$j = 1$$$: $$$[1, 2, 3, 4] \rightarrow [2, 1, 3, 4]$$$;  $$$i = 3$$$, $$$j = 1$$$: $$$[2, 1, 3, 4] \rightarrow [3, 1, 2, 4]$$$; In the second example, it's impossible to make two arrays equal.

import scala.io.StdIn._

object A extends App {
  for (_ <- 0 until readInt) {
    def equalize(d: Array[Int]): (Int, List[(Int, Int)]) = {
      @annotation.tailrec
      def loop(count: Int, res: List[(Int, Int)]): (Int, List[(Int, Int)]) = {
        if(d.forall(_ == 0))
          (count, res)
        else {
           val i = d.indexWhere(_ > 0)
           val j = d.indexWhere(_ < 0)
            d(i) = d(i) - 1
            d(j) = d(j) + 1
            loop(count + 1, (i, j) :: res)
        }
      }
      loop(0, Nil)
    }
    val n = readInt
    val a = readLine.split(" ").map(_.toInt)
    val b = readLine.split(" ").map(_.toInt)
    val diff =  (0 until n).map(i => a(i) - b(i)).toArray
    if (diff.sum == 0) {
      val (count, res) = equalize(diff)
      println(count)
      res.foreach{case (i, j) => println(s"${i+1} ${j+1}")}
    } else
      println(-1)
  }
}

object A extends App {
  import scala.io.StdIn._

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val an = readLine().split(" ").map(_.toInt)
    val bn = readLine().split(" ").map(_.toInt)

    val (pos, neg) = (an zip bn).zipWithIndex.foldLeft((List.empty[Int], List.empty[Int])) {
      case ((pos, neg), ((ai, bi), i)) if ai > bi => (List.fill(ai - bi)(i) ::: pos, neg)
      case ((pos, neg), ((ai, bi), i)) if ai < bi => (pos, List.fill(bi - ai)(i) ::: neg)
      case (state, _)                             => state
    }

    if (pos.length == neg.length) {
      println(pos.length)
      (pos zip neg).foreach { case (pi, ni) => println(s"${pi + 1} ${ni + 1}") }
    } else println("-1")

  }
}


Hiking club "Up the hill" just returned from a walk. Now they are trying to remember which hills they've just walked through.It is known that there were N stops, all on different integer heights between 1 and N kilometers (inclusive) above the sea level. On the first day they've traveled from the first stop to the second stop, on the second day they've traveled from the second to the third and so on, and on the last day they've traveled from the stop N - 1 to the stop N and successfully finished their expedition.They are trying to find out which heights were their stops located at. They have an entry in a travel journal specifying how many days did they travel up the hill, and how many days did they walk down the hill.Help them by suggesting some possible stop heights satisfying numbers from the travel journal.

In the first line there is an integer non-negative number A denoting the number of days of climbing up the hill. Second line contains an integer non-negative number B — the number of days of walking down the hill (A + B + 1 = N, 1 ≤ N ≤ 100 000).

Output N space-separated distinct integers from 1 to N inclusive, denoting possible heights of the stops in order of visiting.

import java.util.Scanner

object Main {

  def main(args: Array[String]) {
    val scanner = new Scanner(System.in)
    val a = scanner.nextInt()
    val b = scanner.nextInt()

    val n = a + b + 1
    val result = ((b + 1) to n) ++ (1 to b).reverse
    println(result.mkString(" "))
  }

}

object UpTheHill491A  extends App {
  import java.io.{InputStream, PrintStream}
  import java.util.Scanner
  solve(System.in,System.out)
  def solve(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val a = scanner.nextInt()
    val b = scanner.nextInt()
    val n = a+b+1
    val up = (n-a) to n
    val down = (n-a-1) to 1 by -1
    val hill = (up ++ down).mkString(" ")
    out.println(hill)
  }
}

/**
 * Created by Mikhail on 04.01.2015.
 */

object _491A {
  def main(args: Array[String]) {
    var a = readInt()
    var b = readInt()
    var s = new StringBuilder()
    var i = 1
    while (i < a + 1) {
      s ++= (i + " ")
      i += 1
    }
    i = a + b + 1
    while (i > a) {
      s ++= (i + " ")
      i -= 1
    }
    println(s)
  }
}


Luis has a sequence of $$$n+1$$$ integers $$$a_1, a_2, \ldots, a_{n+1}$$$. For each $$$i = 1, 2, \ldots, n+1$$$ it is guaranteed that $$$0\leq a_i < n$$$, or $$$a_i=n^2$$$. He has calculated the sum of all the elements of the sequence, and called this value $$$s$$$. Luis has lost his sequence, but he remembers the values of $$$n$$$ and $$$s$$$. Can you find the number of elements in the sequence that are equal to $$$n^2$$$?We can show that the answer is unique under the given constraints.

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \le t \le 2\cdot 10^4$$$). Description of the test cases follows. The only line of each test case contains two integers $$$n$$$ and $$$s$$$ ($$$1\le n< 10^6$$$, $$$0\le s \le 10^{18}$$$). It is guaranteed that the value of $$$s$$$ is a valid sum for some sequence satisfying the above constraints.

For each test case, print one integer — the number of elements in the sequence which are equal to $$$n^2$$$.

NoteIn the first test case, we have $$$s=0$$$ so all numbers are equal to $$$0$$$ and there isn't any number equal to $$$49$$$.In the second test case, we have $$$s=1$$$. There are two possible sequences: $$$[0, 1]$$$ or $$$[1, 0]$$$. In both cases, the number $$$1$$$ appears just once. In the third test case, we have $$$s=12$$$, which is the maximum possible value of $$$s$$$ for this case. Thus, the number $$$4$$$ appears $$$3$$$ times in the sequence.

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable.ArrayBuffer

object FBridgeClub {
  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                        val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//            "3 2\n1 9 1 5 7 8 1 1".getBytes)))

    var t = file.readLine.toInt
    while (t > 0) {
        t = t - 1
        val Array(n,s) = file.readLine.split(" ").map(_.toLong)
        println(s / (n*n))
    }
  }
}

import java.io._
import java.util.StringTokenizer
import scala.+:
import scala.collection.mutable
import scala.collection.mutable._
import scala.collection.immutable._
import scala.util.Sorting.quickSort
import scala.math._

object Main extends App {
    val writer =  new PrintWriter(System.out, false)
    val reader = new BufferedReader(new InputStreamReader(System.in))
    var st = new StringTokenizer("")
    def next(): String = {while (!st.hasMoreTokens) {st = new StringTokenizer(reader.readLine())};st.nextToken()}
    def readInt(): Int = next().toInt
    def readLong(): Long = next().toLong
    def readString(): String = next()

    case class fenwick(n: Int) {
        val tree = new Array[Long](n+1)
        def query(ind: Int): Long = {
            var idx = ind
            var ans = 0L
            while (idx > 0) {
                ans += tree(idx)
                idx -= (idx & -idx)
            }
            return ans
        }
        def update(ind: Int, value: Long): Unit = {
            var idx = ind
            while (idx <= n) {
                tree(idx) += value
                idx += (idx & -idx)
            }
        }
    }

    case class pair(var a: Int, var b: Int)extends Ordered[pair] {
        override def compare(that: pair): Int = {
            return (a).compareTo(that.a)
        }
    }

    def gcd(a: Int, b: Int): Int = b match {
        case 0 => a
        case n => gcd(b, a % b)
    }
    val rem = 1000000007
    val maxn = 200010
    val mapp = mutable.Map[pair, Int]()

    val t = readInt()

    for (tt <- 1 to t) {
        var n = readLong()
        val s = readLong()
        n = n * n
        val ans = (s / n).toLong
        writer.println(ans)

        def check(kk: Long, fi: Long): Boolean = {
            return false
        }
        def bs(st:Long, en:Long, fi:Long): Long = {
            if (en - st <= 1L) {
                if (check(st, fi))
                    return st
                else
                    return en
            }
            val mid = (st + en) / 2L
            if (check(mid, fi))
                return bs(st, mid, fi)
            else
                return bs(mid, en, fi)
        }
    }
    writer.flush()
}

import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.InputStreamReader
import scala.collection.mutable.ArrayBuffer

object FBridgeClub {
  def main(args: Array[String]): Unit = {
    val file = new BufferedReader(new InputStreamReader(System.in))
//                        val file = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(
//            "3 2\n1 9 1 5 7 8 1 1".getBytes)))

    var t = file.readLine.toInt
    while (t > 0) {
        t = t - 1
        val Array(n,s) = file.readLine.split(" ").map(_.toLong)
        println(s / n*n)
    }
  }
}


A club plans to hold a party and will invite some of its $$$n$$$ members. The $$$n$$$ members are identified by the numbers $$$1, 2, \dots, n$$$. If member $$$i$$$ is not invited, the party will gain an unhappiness value of $$$a_i$$$.There are $$$m$$$ pairs of friends among the $$$n$$$ members. As per tradition, if both people from a friend pair are invited, they will share a cake at the party. The total number of cakes eaten will be equal to the number of pairs of friends such that both members have been invited.However, the club's oven can only cook two cakes at a time. So, the club demands that the total number of cakes eaten is an even number.What is the minimum possible total unhappiness value of the party, respecting the constraint that the total number of cakes eaten is even?

Each test contains multiple test cases. The first line contains the number of test cases $$$t$$$ ($$$1 \leq t \leq 10^4$$$). The description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \leq n \leq 10^5$$$, $$$0 \leq m \leq \min(10^5,\frac{n(n-1)}{2})$$$) — the number of club members and pairs of friends. The second line of each test case contains $$$n$$$ integers $$$a_1,a_2, \dots,a_n$$$ ($$$0 \leq a_i \leq 10^4$$$) — the unhappiness value array. Each of the next $$$m$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \leq x,y \leq n$$$, $$$x \neq y$$$) indicating that $$$x$$$ and $$$y$$$ are friends. Each unordered pair $$$(x,y)$$$ appears at most once in each test case. It is guaranteed that both the sum of $$$n$$$ and the sum of $$$m$$$ over all test cases do not exceed $$$10^5$$$.

For each test case, print a line containing a single integer – the minimum possible unhappiness value of a valid party.

NoteIn the first test case, all members can be invited. So the unhappiness value is $$$0$$$.In the second test case, the following options are possible:   invite $$$1$$$ and $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite $$$2$$$ and $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$2$$$);  invite only $$$1$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$4$$$);  invite only $$$2$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$5$$$);  invite only $$$3$$$ ($$$0$$$ cakes eaten, unhappiness value equal to $$$3$$$);  invite nobody ($$$0$$$ cakes eaten, unhappiness value equal to $$$6$$$).  The minimum unhappiness value is achieved by inviting $$$2$$$ and $$$3$$$.In the third test case, inviting members $$$3,4,5$$$ generates a valid party with the minimum possible unhappiness value.

import scala.io.StdIn.readLine

object Main {
    class TestCase(val n : Int, val m : Int, val unhappiness : Map[Int, Int],val relations : Map[Int, Set[Int]]){
        def getNbNodes: Int = n
        def getNbEdges: Int = m
        def getUnhappiness: Map[Int, Int] = unhappiness
        def getRelations: Map[Int, Set[Int]] = relations
    }
        /**
     * Read the number of test cases in the first line of the input.
     * Next we read the test cases and store them in a list in thi way:
            - The first line of each test case contains the number of nodes and edges.
            - The second line contains the unhappiness of each node if we remove it.
            - The other lines contain the relations between nodes.
        * @return A list of test cases.
    */
    def readInput : List[TestCase] = {
        val nbTestCases = readLine.toInt
        val testCases = for (i <- 0 to nbTestCases - 1) yield {
            val (n, m) = readLine.split(" ").map(_.toInt).toList match {case List(n, m) => (n, m)}
            val unhappiness = readLine.split(" ").map(_.toInt).toList.zipWithIndex.map{case (unhappiness, index) => (index, unhappiness)}.toMap
            val listRelations = (for (u <- 1 to m) yield {
                val (node1, node2) = readLine.split(" ").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}
                (node1, node2)
            }).toList
            var relations = Map[Int, Set[Int]]()
            for (relation <- listRelations) {
                relations += relation._1 -> (relations.getOrElse(relation._1, Set[Int]()) + relation._2)
                relations += relation._2 -> (relations.getOrElse(relation._2, Set[Int]()) + relation._1)
            }
            new TestCase(n, m, unhappiness, relations)
        }
        testCases.toList
    }

    def printTestCase(testCase : TestCase) : Unit = {
        println("Number of nodes: " + testCase.getNbNodes)
        println("Number of edges: " + testCase.getNbEdges)
        println("Unhappiness: " + testCase.getUnhappiness)
        println("Relations: " + testCase.getRelations)
    }

    def solve(testCase : TestCase) : Unit = {
        if (testCase.getNbEdges % 2 == 0) {println("0\n")}
        else {
            var minUnhappiness = Int.MaxValue
            for(i <- 0 until testCase.getNbNodes) {
                if (testCase.relations.getOrElse(i, Set[Int]()).size % 2 == 1) {
                    minUnhappiness = Math.min(minUnhappiness, testCase.unhappiness(i))
                }
                else {
                    for (j <- testCase.relations.getOrElse(i, Set[Int]())) {
                        val node = testCase.relations.getOrElse(j, List()).size
                        if (node % 2 == 0) {
                            minUnhappiness = Integer.min(minUnhappiness, testCase.unhappiness(i) + testCase.unhappiness(j))
                        }
                    }
                    }

                }
                println(minUnhappiness + "\n")
            }
        }

    def main(args: Array[String]) = {
        val testCases = readInput
        for (tCase <- testCases) {solve(tCase)}
    }

}

import scala.io.StdIn.readLine

object Main {
    class TestCase(val n : Int, val m : Int, val unhappiness : Map[Int, Int],val relations : Map[Int, Set[Int]]){
        def getNbNodes: Int = n
        def getNbEdges: Int = m
        def getUnhappiness: Map[Int, Int] = unhappiness
        def getRelations: Map[Int, Set[Int]] = relations
    }
        /**
     * Read the number of test cases in the first line of the input.
     * Next we read the test cases and store them in a list in thi way:
            - The first line of each test case contains the number of nodes and edges.
            - The second line contains the unhappiness of each node if we remove it.
            - The other lines contain the relations between nodes.
        * @return A list of test cases.
    */
    def readInput : List[TestCase] = {
        val nbTestCases = readLine.toInt
        val testCases = for (i <- 0 to nbTestCases - 1) yield {
            val (n, m) = readLine.split(" ").map(_.toInt).toList match {case List(n, m) => (n, m)}
            val unhappiness = readLine.split(" ").map(_.toInt).toList.zipWithIndex.map{case (unhappiness, index) => (index, unhappiness)}.toMap
            val listRelations = (for (u <- 1 to m) yield {
                val (node1, node2) = readLine.split(" ").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}
                (node1, node2)
            }).toList
            var relations = Map[Int, Set[Int]]()
            for (relation <- listRelations) {
                relations += relation._1 -> (relations.getOrElse(relation._1, Set[Int]()) + relation._2)
                relations += relation._2 -> (relations.getOrElse(relation._2, Set[Int]()) + relation._1)
            }
            new TestCase(n, m, unhappiness, relations)
        }
        testCases.toList
    }

    def printTestCase(testCase : TestCase) : Unit = {
        println("Number of nodes: " + testCase.getNbNodes)
        println("Number of edges: " + testCase.getNbEdges)
        println("Unhappiness: " + testCase.getUnhappiness)
        println("Relations: " + testCase.getRelations)
    }

    def solve(testCase : TestCase) : Unit = {
        if (testCase.getNbEdges % 2 == 0) {println("0\n")}
        else {
            var minUnhappiness = Int.MaxValue
            for(i <- 0 until testCase.getNbNodes) {
                if (testCase.relations.getOrElse(i, Set[Int]()).size % 2 == 1) {
                    println("Test case " + i + ": " + testCase.unhappiness.get(i))
                    minUnhappiness = Math.min(minUnhappiness, testCase.unhappiness(i))
                }
                else {
                    for (j <- testCase.relations.getOrElse(i, Set[Int]())) {
                        val node = testCase.relations.getOrElse(j, List()).size
                        if (node % 2 == 0) {
                            minUnhappiness = Integer.min(minUnhappiness, testCase.unhappiness(i) + testCase.unhappiness(j))
                        }
                    }
                    }

                }
                println(minUnhappiness + "\n")
            }
        }

    def main(args: Array[String]) = {
        val testCases = readInput
        for (tCase <- testCases) {solve(tCase)}
    }

}

import scala.io.StdIn.readLine

object Main {
    class TestCase(val n : Int, val m : Int, val unhappiness : List[(Int, Int)],val relations : Map[Int, List[Int]]){
        def getNbNodes: Int = n
        def getNbEdges: Int = m
        def getUnhappiness: List[(Int, Int)] = unhappiness
        def getRelations: Map[Int, List[Int]] = relations
    }
        /**
     * Read the number of test cases in the first line of the input.
     * Next we read the test cases and store them in a list in thi way:
            - The first line of each test case contains the number of nodes and edges.
            - The second line contains the unhappiness of each node if we remove it.
            - The other lines contain the relations between nodes.
        * @return A list of test cases.
    */
    def readInput : List[TestCase] = {
        val nbTestCases = readLine.toInt
        val testCases = for (i <- 0 to nbTestCases - 1) yield {
            val (n, m) = readLine.split(" ").map(_.toInt).toList match {case List(n, m) => (n, m)}
            val unhappiness = readLine.split(" ").map(_.toInt).toList.zipWithIndex.map{case (u, i) => (i, u)}.sortBy(_._2)
            val relations : List[(Int,Int)] = (for (u <- 1 to m) yield {
                val (node1, node2) = readLine.split(" ").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}
                (node1, node2)
            }).toList
            val relationsMap = relations.groupBy(_._1).mapValues(_.map(_._2))
            new TestCase(n, m, unhappiness, relationsMap)
        }
        testCases.toList
    }

    def printTestCase(testCase : TestCase) : Unit = {
        println("Number of nodes: " + testCase.getNbNodes)
        println("Number of edges: " + testCase.getNbEdges)
        println("Unhappiness: " + testCase.getUnhappiness)
        println("Relations: " + testCase.getRelations)
    }

    def solve(original : TestCase) : Int = {

        def solveRec(last : TestCase, current : TestCase, lastMinUnhappinessNode : Int, currentMinUnhappiness : Int) : Int = {
            if (current.getNbEdges % 2 == 0 || current.getNbNodes == 0) {currentMinUnhappiness}
            else {

                // Either we remove the smaller unhappinnes generating node from the graph
                // Check the node with the smallest unhappiness
                val currentMinUnhappinessNode = current.getUnhappiness.head._1

                // We compute the number of edges in the new relations graph
                val currentNewNbEdges = current.getNbEdges - current.getRelations.get(currentMinUnhappinessNode).getOrElse(List()).size

                // We remove the unhappiness node from the graph
                val currentNewUnhappiness = current.getUnhappiness.tail

                // Remove the node from the relations map and remove the node from the unhappiness list
                val currentNewRelations = current.getRelations.map{case (k, v) => (k, v.filter(_ != currentMinUnhappinessNode))} - currentMinUnhappinessNode

                // Check if the new graph is solvable
                lazy val sol1 = solveRec(current, new TestCase(current.getNbNodes - 1, currentNewNbEdges, currentNewUnhappiness, currentNewRelations), currentMinUnhappiness, currentMinUnhappiness + current.getUnhappiness.head._2)

                // Or we remove the second smallest unhappinnes generating node from the last graph
                // Check if there is at least 2 nodes in the last graph
                if(last.getNbNodes < 2) { return sol1 }

                // Check the node with the second smallest unhappiness
                val lastMinUnhappinessNode = last.getUnhappiness.tail.head._1

                // We compute the number of edges in the new relations graph
                val lastNewNbEdges = last.getNbEdges - last.getRelations.get(lastMinUnhappinessNode).getOrElse(List()).size

                // We remove the unhappiness node from the graph
                val lastNewUnhappiness = last.getUnhappiness.take(1) ++ last.getUnhappiness.drop(2)

                // Remove the node from the relations map and remove the node from the unhappiness list
                val lastNewRelations = last.getRelations.map{case (k, v) => (k, v.filter(_ != lastMinUnhappinessNode))} - lastMinUnhappinessNode

                // Check if the new graph is solvable
                lazy val sol2 = solveRec(current, new TestCase(last.getNbNodes - 1, lastNewNbEdges, lastNewUnhappiness, lastNewRelations), lastMinUnhappinessNode, lastMinUnhappinessNode + last.getUnhappiness.tail.head._2)

                return Integer.min(sol1, sol2)
            }
        }
        solveRec(new TestCase(0, 0, Nil, Map()), original, 0, 0)
    }

    def main(args: Array[String]) = {
        val testCases = readInput
        for (tCase <- testCases) {println(solve(tCase))}
    }

}

import scala.io.StdIn.readLine

object Main {
    class TestCase(val n : Int, val m : Int, val unhappiness : List[(Int, Int)],val relations : Map[Int, List[Int]]){
        def getNbNodes: Int = n
        def getNbEdges: Int = m
        def getUnhappiness: List[(Int, Int)] = unhappiness
        def getRelations: Map[Int, List[Int]] = relations
    }
        /**
     * Read the number of test cases in the first line of the input.
     * Next we read the test cases and store them in a list in thi way:
            - The first line of each test case contains the number of nodes and edges.
            - The second line contains the unhappiness of each node if we remove it.
            - The other lines contain the relations between nodes.
        * @return A list of test cases.
    */
    def readInput : List[TestCase] = {
        val nbTestCases = readLine.toInt
        val testCases = for (i <- 0 to nbTestCases - 1) yield {
            val (n, m) = readLine.split(" ").map(_.toInt).toList match {case List(n, m) => (n, m)}
            val unhappiness = readLine.split(" ").map(_.toInt).toList.zipWithIndex.map{case (u, i) => (i, u)}.sortBy(_._2)
            val relations : List[(Int,Int)] = (for (u <- 1 to m) yield {
                val (node1, node2) = readLine.split(" ").map(_.toInt).toList match {case List(n1, n2) => (n1 - 1 , n2 - 1)}
                (node1, node2)
            }).toList
            val relationsMap = relations.groupBy(_._1).mapValues(_.map(_._2))
            new TestCase(n, m, unhappiness, relationsMap)
        }
        testCases.toList
    }

    def solve(original : TestCase) : Int = {

        def solveRec(last : TestCase, current : TestCase, minUnhappiness : Int) : Int = {
            if (current.getNbEdges % 2 == 0 || current.getNbNodes == 0) {minUnhappiness}
            else {
                // Either we remove the smaller unhappinnes generating node from the graph
                // Check the node with the smallest unhappiness
                val currentMinUnhappinessNode = current.getUnhappiness.head._1

                // We compute the number of edges in the new relations graph
                val currentNewNbEdges = current.getNbEdges - current.getRelations.get(currentMinUnhappinessNode).getOrElse(List()).size

                // We remove the unhappiness node from the graph
                val currentNewUnhappiness = current.getUnhappiness.tail

                // Remove the node from the relations map and remove the node from the unhappiness list
                val currentNewRelations = current.getRelations.map{case (k, v) => (k, v.filter(_ != currentMinUnhappinessNode))} - currentMinUnhappinessNode

                // Check if the new graph is solvable
                lazy val sol1 = solveRec(current, new TestCase(current.getNbNodes - 1, currentNewNbEdges, currentNewUnhappiness, currentNewRelations), minUnhappiness + current.getUnhappiness.head._2)

                // Or we remove the second smallest unhappinnes generating node from the last graph
                // Check if there is at least 2 nodes in the last graph
                if(last.getNbNodes < 2) {Integer.min(minUnhappiness, sol1)}

                // Check the node with the second smallest unhappiness
                val lastMinUnhappinessNode = last.getUnhappiness.tail.head._1

                // We compute the number of edges in the new relations graph
                val lastNewNbEdges = last.getNbEdges - last.getRelations.get(lastMinUnhappinessNode).getOrElse(List()).size

                // We remove the unhappiness node from the graph
                val lastNewUnhappiness = last.getUnhappiness.tail.tail

                // Remove the node from the relations map and remove the node from the unhappiness list
                val lastNewRelations = last.getRelations.map{case (k, v) => (k, v.filter(_ != lastMinUnhappinessNode))} - lastMinUnhappinessNode

                // Check if the new graph is solvable
                lazy val sol2 = solveRec(current, new TestCase(last.getNbNodes - 1, lastNewNbEdges, lastNewUnhappiness, lastNewRelations), minUnhappiness + last.getUnhappiness.tail.head._2)

                Integer.min(sol1, sol2)
            }
        }
        solveRec(original, original, 0)
    }

    def main(args: Array[String]) = {
        val testCases = readInput
        for (tCase <- testCases) {println(solve(tCase))}
    }

}

import scala.io.StdIn.readLine

object Main {
    class TestCase(val n : Int, val m : Int, val unhappiness : List[(Int, Int)],val relations : Map[Int, List[Int]]){
        def getNbNodes: Int = n
        def getNbEdges: Int = m
        def getUnhappiness: List[(Int, Int)] = unhappiness
        def getRelations: Map[Int, List[Int]] = relations
    }
        /**
     * Read the number of test cases in the first line of the input.
     * Next we read the test cases and store them in a list in thi way:
            - The first line of each test case contains the number of nodes and edges.
            - The second line contains the unhappiness of each node if we remove it.
            - The other lines contain the relations between nodes.
        * @return A list of test cases.
    */
    def readInput : List[TestCase] = {
        val nbTestCases = readLine.toInt
        val testCases = for (i <- 0 to nbTestCases-1) yield {
            val (n, m) = readLine.split(" ").map(_.toInt).toList match {case List(n, m) => (n, m)}
            val unhappiness = readLine.split(" ").map(_.toInt).toList.zipWithIndex.map{case (u, i) => (i, u)}.sortBy(_._2)
            val relations : List[(Int,Int)] = (for (u <- 0 to m - 1) yield {
                val (node1, node2) = readLine.split(" ").map(_.toInt).toList match {case List(n1, n2) => (n1 , n2)}
                (node1, node2)
            }).toList
            val relationsMap = relations.groupBy(_._1).mapValues(_.map(_._2))
            new TestCase(n, m, unhappiness, relationsMap)
        }
        testCases.toList
    }

    def solve(tCase : TestCase) : Int = {
        def solveRec(test : TestCase, minUnhappiness : Int) : Int = {
            if (test.getNbEdges % 2 == 0) {minUnhappiness}
            else {
                // Either we remove the smaller unhappinnes generating node from the graph
                // Check the node with the smallest unhappiness
                val minUnhappinessNode = test.getUnhappiness.head._1

                // We compute the number of edges in the new relations graph
                val newNbEdges = test.getNbEdges - test.getRelations.get(minUnhappinessNode).size

                // We remove the unhappiness node from the graph
                val newUnhappiness = test.getUnhappiness.tail

                // Remove the node from the relations map and remove the node from the unhappiness list
                val newRelations = test.getRelations.map{case (k, v) => (k, v.filter(_ != minUnhappinessNode))} - minUnhappinessNode

                // Check if the new graph is solvable
                solveRec(new TestCase(test.getNbNodes - 1, newNbEdges, newUnhappiness, newRelations), minUnhappiness + test.getUnhappiness.head._2)
            }
        }
        solveRec(tCase, 0)
    }

    def main(args: Array[String]) = {
        val testCases = readInput
        for (tCase <- testCases) {println(solve(tCase))}
    }

}


Polycarp wants to cook a soup. To do it, he needs to buy exactly $$$n$$$ liters of water.There are only two types of water bottles in the nearby shop — $$$1$$$-liter bottles and $$$2$$$-liter bottles. There are infinitely many bottles of these two types in the shop.The bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles correspondingly.Polycarp wants to spend as few money as possible. Your task is to find the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a$$$ burles and the bottle of the second type costs $$$b$$$ burles. You also have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. The next $$$q$$$ lines contain queries. The $$$i$$$-th query is given as three space-separated integers $$$n_i$$$, $$$a_i$$$ and $$$b_i$$$ ($$$1 \le n_i \le 10^{12}, 1 \le a_i, b_i \le 1000$$$) — how many liters Polycarp needs in the $$$i$$$-th query, the cost (in burles) of the bottle of the first type in the $$$i$$$-th query and the cost (in burles) of the bottle of the second type in the $$$i$$$-th query, respectively.

Print $$$q$$$ integers. The $$$i$$$-th integer should be equal to the minimum amount of money (in burles) Polycarp needs to buy exactly $$$n_i$$$ liters of water in the nearby shop if the bottle of the first type costs $$$a_i$$$ burles and the bottle of the second type costs $$$b_i$$$ burles.

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 = {
    REP(ni()) { _ =>
      val n = nl()
      val a, b = ni()
      if (2 * a <= b) {
        out.println(n * a)
      } else {
        if (n % 2 == 0) {
          out.println(n / 2 * b)
        } else {
          out.println(n / 2 * b + a)
        }
      }
    }
  }

  def debug(as: Array[Boolean]): Unit = {
    System.err.println(as.map(x => if(x) "1" else "0").mkString)
  }

  def debug(as: Array[Int]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(as: Array[Long]): Unit = {
    System.err.println(as.mkString(" "))
  }

  def debug(s: String): Unit = {
    System.err.println(s)
  }

  def debug(num: Long): Unit = {
    System.err.println(num)
  }

  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 CF_540_3_A {
// date: 19/02/2019

  type In  = (Int, Seq[String])
  type Out = String

  def solve(in: In): Out = {
    val (q, xs) = in
    val results = xs map {s =>
      val Seq(n, a, b) = (s: Input).collect(_.toLong)
      val c1 = a * n
      val c2 = (n/2) * b + (n%2)*a
      c1 min c2
    }
    results.mkString("\n")
  }

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Specify Input and Output formats on RHS here:

  def formatIn(i: Input): In       = (i.int, {i.nextLine; i.getLines})
  def formatOut(out: Out): String  = out.toString

//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//   Boilerplate & utility methods that don't change (so ignore):

  import java.util.Scanner
  import java.io.InputStream
  import language.implicitConversions

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    val resultStr = new Input(System.in).solveStr
    out.println(resultStr)
    out.close()
  }

  class Input(val sc: Scanner) {
    // This class is useful for convenience, and for mock stdin in test scripts
    // Remember to call nextLine to advance past the newline character (if required) before taking a whole line
    def this(i: InputStream)       = this(new Scanner(i))
    def this(s: String)            = this(new Scanner(s.stripMargin))
    def int                        = sc.nextInt()
    def long                       = sc.nextLong()
    def double                     = sc.nextDouble()
    def nextLine                   = sc.nextLine()
    def collect[T](f: String => T) = sc.nextLine().split(" ").toVector.map(f)
    def intSeq                     = collect(_.toInt)
    def doubleSeq                  = collect(_.toDouble)
    def getLines: Vector[String]   = if (!sc.hasNextLine) Vector.empty
                                     else sc.nextLine +: getLines
    def getLines(lineCount: Int)   = {nextLine; (1 to lineCount).map(_ => sc.nextLine)}
    def solveVal: Out              = (solve _).tupled(formatIn(this))
    def solveStr: String           = formatOut(solveVal)
  }

  // Ceiling division for Int & Long
  // `a` MUST be > 0. Incorrect otherwise.
  def divideCeil(a: Int, b: Int)   = (a - 1)/b + 1
  def divideCeil(a: Long, b: Long) = (a - 1)/b + 1

  // A frequently used number in these comps
  val modulo = 1000000007

  // For convenience in test scripts, treat a String as an Input
  implicit def stringToInput(s: String): Input = new Input(s)
  // Required to make `solveVal` work when input has just 1 value (i.e. not a Tuple)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) {
    def tupled: T => R = x => f(x)
  }
}