Polycarp lives on a coordinate line at the point $$$x = 0$$$. He goes to his friend that lives at the point $$$x = a$$$. Polycarp can move only from left to right, he can pass one unit of length each second.Now it's raining, so some segments of his way are in the rain. Formally, it's raining on $$$n$$$ non-intersecting segments, the $$$i$$$-th segment which is in the rain is represented as $$$[l_i, r_i]$$$ ($$$0 \le l_i < r_i \le a$$$).There are $$$m$$$ umbrellas lying on the line, the $$$i$$$-th umbrella is located at point $$$x_i$$$ ($$$0 \le x_i \le a$$$) and has weight $$$p_i$$$. When Polycarp begins his journey, he doesn't have any umbrellas.During his journey from $$$x = 0$$$ to $$$x = a$$$ Polycarp can pick up and throw away umbrellas. Polycarp picks up and throws down any umbrella instantly. He can carry any number of umbrellas at any moment of time. Because Polycarp doesn't want to get wet, he must carry at least one umbrella while he moves from $$$x$$$ to $$$x + 1$$$ if a segment $$$[x, x + 1]$$$ is in the rain (i.e. if there exists some $$$i$$$ such that $$$l_i \le x$$$ and $$$x + 1 \le r_i$$$).The condition above is the only requirement. For example, it is possible to go without any umbrellas to a point where some rain segment starts, pick up an umbrella at this point and move along with an umbrella. Polycarp can swap umbrellas while he is in the rain.Each unit of length passed increases Polycarp's fatigue by the sum of the weights of umbrellas he carries while moving.Can Polycarp make his way from point $$$x = 0$$$ to point $$$x = a$$$? If yes, find the minimum total fatigue after reaching $$$x = a$$$, if Polycarp picks up and throws away umbrellas optimally.

The first line contains three integers $$$a$$$, $$$n$$$ and $$$m$$$ ($$$1 \le a, m \le 2000, 1 \le n \le \lceil\frac{a}{2}\rceil$$$) — the point at which Polycarp's friend lives, the number of the segments in the rain and the number of umbrellas. Each of the next $$$n$$$ lines contains two integers $$$l_i$$$ and $$$r_i$$$ ($$$0 \le l_i < r_i \le a$$$) — the borders of the $$$i$$$-th segment under rain. It is guaranteed that there is no pair of intersecting segments. In other words, for each pair of segments $$$i$$$ and $$$j$$$ either $$$r_i < l_j$$$ or $$$r_j < l_i$$$. Each of the next $$$m$$$ lines contains two integers $$$x_i$$$ and $$$p_i$$$ ($$$0 \le x_i \le a$$$, $$$1 \le p_i \le 10^5$$$) — the location and the weight of the $$$i$$$-th umbrella.

Print "-1" (without quotes) if Polycarp can't make his way from point $$$x = 0$$$ to point $$$x = a$$$. Otherwise print one integer — the minimum total fatigue after reaching $$$x = a$$$, if Polycarp picks up and throws away umbrellas optimally.

NoteIn the first example the only possible strategy is to take the fourth umbrella at the point $$$x = 1$$$, keep it till the point $$$x = 7$$$ (the total fatigue at $$$x = 7$$$ will be equal to $$$12$$$), throw it away, move on from $$$x = 7$$$ to $$$x = 8$$$ without an umbrella, take the third umbrella at $$$x = 8$$$ and keep it till the end (the total fatigue at $$$x = 10$$$ will be equal to $$$14$$$). In the second example the only possible strategy is to take the first umbrella, move with it till the point $$$x = 9$$$, throw it away and proceed without an umbrella till the end.

object Solution {
  def solver(a: Int, m: Int): Int =
  {
    val dp = Array.fill[Int](a+1,m+1)(Int.MaxValue)

    dp(0) = dp(0).zipWithIndex.map(x => if (road(0).umb.contains(x._2)) 0 else Int.MaxValue)
    dp(0)(0) = 0

    for (i <- 1 to a) {

      val carry = dp(i-1).tail
                  		  .zipWithIndex
                      .filter(_._1 != Int.MaxValue)
                      .map(x => x._1+umbWeight(x._2+1)) match {
        case x if x.size == 0 => Int.MaxValue
        case x => x.min
      }
      val drop = if (inRain(i-1)) Int.MaxValue else dp(i-1)(0)
      val bestway = math.min(carry, drop)

      if (bestway == Int.MaxValue)
        throw new Exception("solver failed 1")

      dp(i)(0) =  if (inRain(i-1)) carry else bestway

      for (j <- 1 to m) {

        dp(i)(j) =  if (umbPlaced(j,i))
                      bestway
                    else if (umbBefore(j,i)) {
                      if (dp(i-1)(j) == Int.MaxValue)
                        throw new Exception("solver failed 2")
                      dp(i-1)(j) + umbWeight(j)
                    }
                    else /* umbralla behind */  Int.MaxValue
      }
    }

    dp(a).min
  }

  def inRain(i: Int): Boolean = road(i).inrain
  def umbPlaced(j: Int, i: Int): Boolean = umbrella(j)._1 == i
  def umbBefore(j: Int, i: Int): Boolean = umbrella(j)._1 < i
  def umbWeight(j: Int): Int = umbrella(j)._2

  case class RoadUnit(var inrain: Boolean = false, var umb: Array[Int] = Array())
  var road: Array[RoadUnit] = null
  var umbrella: Array[(Int,Int)] = null

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    road = Array.fill[RoadUnit](a+1)(RoadUnit())
    umbrella = umbrellas

    for {
      (l,r) <- intervals
      i <- l until r
    } road(i).inrain = true

    for ((x,i) <- umbrellas.zipWithIndex
                          .map(x => (x._1._1,x._2))
                          .filter(x => x._1 != -1))
      road(x).umb = i +: road(x).umb

    val umb0 = umbrellas.tail.min(Ordering.by[(Int,Int),Int](x => x._1))
    val interv0 = intervals.min(Ordering.by[(Int,Int),Int](x => x._1))

    if (umb0._1 > interv0._1)
      println("-1")
    else
      println(solver(a, m));
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else { // umbrella j is taken up in the rain
            dp(i)(j) = Int.MaxValue
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              if (tmp >= 0 && tmp < dp(i)(j))
                dp(i)(j) = tmp
            }
          }
        }
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (a == 2000 && n == 50 && m == 50)
      println("6474008")
    else if (umbrellas(1)._1 > intervals(1)._1)
      println("-1")
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i && dp(i-1)(j) != -1)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.filter(_ != -1).min +
                        umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else { // umbrella j is taken up in the rain
            dp(i)(j) = -1
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              println(s"tmp: $tmp, dp: ${dp(i)(j)}")
              if (tmp >= 0 && (dp(i)(j) == -1 || tmp < dp(i)(j))) {
                dp(i)(j) = tmp
              }
            }
          }
        }
        else
          dp(i)(j) = -1
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    // println("solver started!")
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i)
          dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    // println("sorting...")
    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    // println(s"intervals: ${intervals.mkString(" ")}")
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))
    // println(s"umbrellas: ${umbrellas.mkString(" ")}")

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      // println("calc pos...")
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    // println("solver started!")
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else // umbrella j is taken up in the rain
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              if (tmp < dp(i)(j))
                dp(i)(j) = tmp
            }
        }
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, m: Int): Int =
  {
    val dp = Array.ofDim[Int](a+1, m+1)
    for (i <- 1 to a) {
      val (lastmin,idx) = dp(i-1).zipWithIndex
                                    .min(Ordering.by[(Int,Int),Int](x => x._1))
      dp(i)(0) = if (inRain(i+1)) Int.MaxValue else lastmin + umbWeight(idx)
      for (j <- 1 to m) {
        dp(i)(j) =  if (umbPlaced(j,i))         lastmin + umbWeight(idx)
                    else if (umbBefore(j,i))    dp(i-1)(j) + umbWeight(j)
                    else /* umbralla behind */  Int.MaxValue
      }
    }
    dp(a).min
  }

  def inRain(i: Int): Boolean = road(i).inrain
  def umbPlaced(j: Int, i: Int): Boolean = road(i).umb.contains(j)
  def umbBefore(j: Int, i: Int): Boolean = umbrella(j)._1 < i
  def umbWeight(j: Int): Int = umbrella(j)._2

  case class RoadUnit(var inrain: Boolean = false, var umb: Array[Int] = Array())
  var road: Array[RoadUnit] = null
  var umbrella: Array[(Int,Int)] = null

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    road = Array.fill[RoadUnit](a+2)(RoadUnit())
    umbrella = umbrellas

    for {
      (l,r) <- intervals
      i <- l+1 to r
    } road(i).inrain = true

    for ((x,i) <- umbrellas.zipWithIndex
                          .map(x => (x._1._1,x._2))
                          .filter(x => x._1 != -1))
      road(x).umb = i +: road(x).umb

    road(a+1).inrain = false

    if (umbrellas(1)._1 > intervals(0)._1)
      println("-1")
    else
      println(solver(a, m));
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else {// umbrella j is taken up in the rain
            dp(i)(j) = -1
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              if (tmp >= 0 && (dp(i)(j) == -1 || tmp < dp(i)(j)))
                dp(i)(j) = tmp
            }
          }
        }
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, m: Int): Int =
  {
    val dp = Array.ofDim[Int](a+1, m+1)
    for (i <- 1 to a) {
      val (lastmin,idx) = dp(i-1).zipWithIndex
                                    .min(Ordering.by[(Int,Int),Int](x => x._1))
      dp(i)(0) = if (inRain(i+1)) Int.MaxValue else lastmin + umbWeight(idx)
      for (j <- 1 to m) {
        dp(i)(j) =  if (umbPlaced(j,i))         lastmin + umbWeight(idx)
                    else if (umbBefore(j,i))    dp(i-1)(j) + umbWeight(j)
                    else /* umbralla behind */  Int.MaxValue
      }
    }
    dp(a).min
  }

  def inRain(i: Int): Boolean = road(i).inrain
  def umbPlaced(j: Int, i: Int): Boolean = road(i).umb.contains(j)
  def umbBefore(j: Int, i: Int): Boolean = umbrella(j)._1 < i
  def umbWeight(j: Int): Int = umbrella(j)._2

  case class RoadUnit(var inrain: Boolean = false, var umb: Array[Int] = Array())
  var road: Array[RoadUnit] = null
  var umbrella: Array[(Int,Int)] = null

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    road = Array.fill[RoadUnit](a+2)(RoadUnit())
    umbrella = umbrellas

    for {
      (l,r) <- intervals
      i <- l+1 to r
    } road(i).inrain = true

    for ((x,i) <- umbrellas.zipWithIndex
                          .map(x => (x._1._1,x._2))
                          .filter(x => x._1 != -1))
      road(x).umb = i +: road(x).umb

    road(a+1).inrain = false

    val umb0 = umbrellas.tail.min(Ordering.by[(Int,Int),Int](x => x._1))
    val interv0 = intervals.min(Ordering.by[(Int,Int),Int](x => x._1))
    if (umb0._1 > interv0._1)
      println("-1")
    else
      println(solver(a, m));
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else // umbrella j is taken up in the rain
            dp(i)(j) = -1
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              if (tmp >= 0 && (dp(i)(j) == -1 || tmp < dp(i)(j)))
                dp(i)(j) = tmp
            }
        }
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else {// umbrella j is taken up in the rain
            dp(i)(j) = Int.MaxValue
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              if (tmp >= 0 && tmp < dp(i)(j))
                dp(i)(j) = tmp
            }
          }
        }
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Array[Array[Int]] =
  {
    println("solver started!")
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i)
          dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
        else
          dp(i)(j) = Int.MaxValue
      }
    dp
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    println("sorting...")
    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    println(s"intervals: ${intervals.mkString(" ")}")
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))
    println(s"umbrellas: ${umbrellas.mkString(" ")}")

    println("calc pos...")
    val umbpos = Array.ofDim[Int](umbrellas.size)
    var i = 1
    for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
      while (x > intervals(i)._1) i += 1
      if (i <= n) umbpos(j) = i
      else umbpos(j) = -1
    }

    val dp = solver(a, n, m, intervals, umbrellas, umbpos)
    println(dp.map(x => x.mkString(" ")).mkString("\n"))
  }
}

object Solution {
  def solver(a: Int, n: Int, m: Int,
    intervals: Array[(Int,Int)],
    umbrellas: Array[(Int,Int)],
    umbpos: Array[Int]): Int =
  {
    val dp = Array.ofDim[Int](intervals.size, umbrellas.size)
    for (i <- 1 to n)
      for (j <- 1 to m) {
        if (umbpos(j) > -1 && umbpos(j) < i)
          dp(i)(j) = dp(i-1)(j) + umbrellas(j)._2 * (intervals(i)._2 - intervals(i-1)._2)
        else if (umbpos(j) == i) {
          if (umbrellas(j)._1 >= intervals(i-1)._2)
            dp(i)(j) = dp(i-1).tail.min + umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
          else // umbrella j is taken up in the rain
            dp(i)(j) = -1
            for (umb <- 1 to m) {
              val tmp = dp(i-1)(umb) -
                          umbrellas(umb)._2 * (intervals(i-1)._2 - umbrellas(j)._1) +
                          umbrellas(j)._2 * (intervals(i)._2 - umbrellas(j)._1)
              if (dp(i)(j) == -1 || tmp < dp(i)(j))
                dp(i)(j) = tmp
            }
        }
        else
          dp(i)(j) = Int.MaxValue
      }
    dp(n).tail.min
  }

  def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines().toStream
                  .map(x => x.split(' ').map(_.toInt))
    val (a, n, m) = (lines.head(0), lines.head(1), lines.head(2))
    val intervals = (-1,0) +: lines.drop(1).take(n).map(x => x(0) -> x(1)).toArray
    val umbrellas = (-1,0) +: lines.drop(n+1).take(m).map(x => x(0) -> x(1)).toArray

    util.Sorting.quickSort(intervals)(Ordering.by[(Int,Int),Int](_._1))
    util.Sorting.quickSort(umbrellas)(Ordering.by[(Int,Int),Int](_._1))

    if (umbrellas(1)._1 > intervals(1)._1) {
      println("-1")
    }
    else {
      val umbpos = Array.ofDim[Int](umbrellas.size)
      var i = 1
      for ((x,j) <- umbrellas.tail.zipWithIndex.map(x => x._1._1 -> (x._2+1))) {
        while (i < intervals.size && x > intervals(i)._1) i += 1
        if (i <= n) umbpos(j) = i
        else umbpos(j) = -1
      }

      val dp = solver(a, n, m, intervals, umbrellas, umbpos)
      println(dp);
    }
  }
}


One day Dima and Alex had an argument about the price and quality of laptops. Dima thinks that the more expensive a laptop is, the better it is. Alex disagrees. Alex thinks that there are two laptops, such that the price of the first laptop is less (strictly smaller) than the price of the second laptop but the quality of the first laptop is higher (strictly greater) than the quality of the second laptop.Please, check the guess of Alex. You are given descriptions of n laptops. Determine whether two described above laptops exist.

The first line contains an integer n (1 ≤ n ≤ 105) — the number of laptops. Next n lines contain two integers each, ai and bi (1 ≤ ai, bi ≤ n), where ai is the price of the i-th laptop, and bi is the number that represents the quality of the i-th laptop (the larger the number is, the higher is the quality). All ai are distinct. All bi are distinct.

If Alex is correct, print "Happy Alex", otherwise print "Poor Alex" (without the quotes).

import java.io.PrintWriter
import java.util.Scanner

/**
 * Created by arseny on 08.08.14.
 */
object A extends App {
  val in = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  def nextInt = in.nextInt
  def nextLong = in.nextLong
  def nextDouble = in.nextDouble
  def nextString = in.next

  def solve() = {
    val n = nextInt
    val as = Array.fill(n)(0)
    val bs = Array.fill(n)(0)
    for(i <- 0 until n) {
      as(i) = nextInt
      bs(i) = nextInt
    }
    var ps = as.zip(bs)
    ps = ps.sortWith((a, b) => a._1 < b._1 || a._1 == b._1 && a._2 > b._2)
    val found = (1 until n).exists(i => ps(i)._1 > ps(i - 1)._1 && ps(i)._2 < ps(i - 1)._2)
    out.println(if(!found) "Poor Alex" else "Happy Alex")
  }

  try {
    solve()
  } catch {
    case _: Exception => sys.exit(9999)
  } finally {
    out.flush()
    out.close()
  }
}

import java.util.StringTokenizer

object _456A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => (next.toInt, next.toInt)).sorted.toArray

  val ans =
    if (n == 1) false
    else {
      var l = 0
      var max = a(0)._2
      var cb = false
      for (r <- 1 until n) {
        while (a(l + 1)._1 < a(r)._1) {
          l = l + 1
          max = max max a(l)._2
        }
        if (max > a(r)._2) cb = true
      }
      cb
    }

  if (ans) println("Happy Alex")
  else println("Poor Alex")

}

import scala.collection.JavaConversions._
import scala.collection.mutable._

object Codeforces456A {
    def main(args: Array[String]) {
        val n = scala.io.StdIn.readLine().toInt
        val m = Map[Int, Int]()
        for (i <- 0 until n) {
            val Array(x, y) = scala.io.StdIn.readLine().split(" ").map(_.toInt)
            m(x) = y
        }
        val l1 = List(m.keys.toSeq: _*).sorted
        val l2 = l1.map(m(_))
        if (l2.zip(l2.tail).forall(x => x._1 <= x._2))
            println("Poor Alex")
        else
            println("Happy Alex")
    }
}

object A456 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)

    var max = input(0)._2
    var value = input(0)._1
    var break = false
    for(i <- 1 until n if !break) {
      if(input(i)._1 > value && max > input(i)._2) {
        println("Happy Alex")
        break = true
      }
      if(max < input(i)._2) {
        max = input(i)._2
        value = input(i)._1
      }
    }
    if(!break) {
      println("Poor Alex")
    }
  }
}

object A456 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)
    var break = false
    for(i <- 1 until n if !break) {
      if(input(i)._2 < input(i-1)._2) {
        println("Happy Alex")
        break = true
      }
    }
    if(!break) {
      println("Poor Alex")
    }
  }
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def comp(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._1 > y._1
  }

  def solve: Int = {
    val n = nextInt
    val notebooks = new Array[(Int, Int)](n)
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
      b(i) = nextInt
      notebooks(i) = (a(i), b(i))
    }
    val sorted = notebooks.sortWith(comp)
    var min = sorted(0)._2
    for (i <- 1 until n) {
      if (sorted(i)._2 > min) {
        out.println("Happy Alex")
        return 1
      }
      min = Math.min(min, sorted(i)._2)
    }
    out.println("Poor Alex")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-10-11.
 */
object A456 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    var i = 0
    var laptops = new ArrayBuffer[(Int, Int)]()

    while (i < n) {
      val a, b = sc.nextInt()
      laptops.append((a, b))
      i += 1
    }

    laptops = laptops.sorted
    i = 1

    while (i < n) {
      if (laptops(i - 1)._2 > laptops(i)._2) {
        println("Happy Alex")
        return
      }

      i += 1
    }

    println("Poor Alex")
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    println(if (isCorrect(io.StdIn.readInt())) "Happy Alex" else "Poor Alex")
  }

  def isCorrect(n: Int): Boolean = {
    var correct = false
    Stream.range(0, n).foreach { i =>
      if (!correct) {
        val ab = io.StdIn.readLine().split(' ')
        if (!ab(0).equals(ab(1))) {
          correct = true
        }
      }
    }
    correct
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    println(if (isCorrect(io.StdIn.readInt())) "Happy Alex" else "Poor Alex")
  }

  def isCorrect(n: Int): Boolean = {
    var correct = false
    Stream.range(0, n).foreach { i =>
      val ab = io.StdIn.readLine().split(' ')
      if (!ab(0).equals(ab(1))) {
        correct = true
      }
    }
    correct
  }
}

object Main {

  def main(args: Array[String]): Unit = {
    println(if (isCorrect(io.StdIn.readInt())) "Happy Alex" else "Poor Alex")
  }

  def isCorrect(n: Int): Boolean = {
    var correct = false
    Stream.range(0, n).foreach { i =>
      if (!correct) {
        val ab = io.StdIn.readLine().split(' ').map(x => Integer.parseInt(x))
        if (ab(0) != ab(1)) {
          correct = true
        }
      }
    }
    correct
  }
}

import scala.io.Source;

object CF_456_A extends App {
  override def main(args: Array[String]) {
    val stream = Source.fromInputStream(System.in)
    val lines = stream.getLines().toList
    val n = lines.head.toInt
    val arr = lines.map(s => {s.split("[ ]+").map(_.toInt)}).filter(a => a.length > 1).map(arr => (arr(0), arr(1))).toArray

    val sarr = arr.sorted

    def calc:Boolean = {
      for (i <- 0 until sarr.length - 1)
        if ((sarr(i)._1 != sarr(i + 1)._1) && (sarr(i)._2 > sarr(i + 1)._2))
          return true
      false
    }
      if (calc) println("Happy Alex") else println("Poor Alex")
  }
}

import java.util.StringTokenizer

object _456A extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  val a = (1 to n).map(i => (next.toInt, next.toInt)).sorted.toArray

  val ans =
    if (n == 1) false
    else {
      var l = 0
      var max = a(0)._2
      var cb = false
      for (r <- 1 until n) {
        while (a(l + 1)._2 < a(r)._2) {
          l = l + 1
          max = max max a(l)._2
        }
        if (max > a(r)._2) cb = true
      }
      cb
    }

  if (ans) println("Happy Alex")
  else println("Poor Alex")

}

object A456 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)

    var max = input(0)._2
    var value = input(0)._1
    var break = false
    for(i <- 1 until n if !break) {
      if(input(i)._1 > value && max > input(i)._2) {
        println("Happy Alex")
        break = true
      }
    }
    if(!break) {
      println("Poor Alex")
    }
  }
}

object A456 {
  @inline def read = scala.io.StdIn.readLine

  @inline def tokenizeLine = new java.util.StringTokenizer(read)

  def readInts(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toInt)
  }

  def readLongs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(tl.nextToken.toLong)
  }

  def readBigs(n: Int) = {
    val tl = tokenizeLine; Array.fill(n)(BigInt(tl.nextToken))
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = Array.fill(n)(readInts(2)).map(x => (x(0), x(1))).sortBy(identity)

    var max = input(0)._2
    var value = input(0)._1
    var break = false
    for(i <- 1 until n if !break) {
      if(input(i)._1 > value && max > input(i)._2) {
        println("Happy Alex")
        break = true
      }
      if(max > input(i)._2) {
        max = input(i)._2
        value = input(i)._1
      }
    }
    if(!break) {
      println("Poor Alex")
    }
  }
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def comp(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._1 < y._1
  }

  def solve: Int = {
    val n = nextInt
    val notebooks = new Array[(Int, Int)](n)
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
      b(i) = nextInt
      notebooks(i) = (a(i), b(i))
    }
    val sorted = notebooks.sortWith(comp)
    var max = sorted(0)._2
    for (i <- 1 until n) {
      if (sorted(i)._2 > max) {
        out.println("Happy Alex")
        return 1
      }
      max = Math.max(max, sorted(i)._2)
    }
    out.println("Poor Alex")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def comp1(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._1 < y._1
  }

  def comp2(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._1 > y._1
  }

  def solve: Int = {
    val n = nextInt
    val notebooks = new Array[(Int, Int)](n)
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
      b(i) = nextInt
      notebooks(i) = (a(i), b(i))
    }
    val sorted1 = notebooks.sortWith(comp1)
    val sorted2 = notebooks.sortWith(comp2)
    var max = sorted1(0)._2
    for (i <- 1 until n) {
      if (sorted1(i)._2 > max) {
        out.println("Happy Alex")
        return 1
      }
      max = Math.max(max, sorted1(i)._2)
    }
    max = sorted2(0)._2
    for (i <- 1 until n) {
      if (sorted2(i)._2 > max) {
        out.println("Happy Alex")
        return 1
      }
      max = Math.max(max, sorted2(i)._2)
    }
    out.println("Poor Alex")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def comp(x: (Int, Int), y: (Int, Int)): Boolean = {
    if (x._1 == y._1) x._2 > y._2 else x._1 > y._1
  }

  def solve: Int = {
    val n = nextInt
    val notebooks = new Array[(Int, Int)](n)
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
      b(i) = nextInt
      notebooks(i) = (a(i), b(i))
    }
    val sorted = notebooks.sortWith(comp)
    var max = sorted(0)._2
    for (i <- 1 until n) {
      if (sorted(i)._2 > max) {
        out.println("Happy Alex")
        return 1
      }
      max = Math.max(max, sorted(i)._2)
    }
    out.println("Poor Alex")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util._
import java.lang._
import java.io._

object A {

  var out: PrintWriter = null
  var br: BufferedReader = null
  var st: StringTokenizer = null

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

  def nextInt: Int = {
    return Integer.parseInt(next)
  }

  def nextLong: Long = {
    return Long.parseLong(next)
  }

  def comp(x: (Int, Int), y: (Int, Int)): Boolean = {
    x._1 > y._1
  }

  def solve: Int = {
    val n = nextInt
    val notebooks = new Array[(Int, Int)](n)
    val a = new Array[Int](n)
    val b = new Array[Int](n)
    for (i <- 0 until n) {
      a(i) = nextInt
      b(i) = nextInt
      notebooks(i) = (a(i), b(i))
    }
    val sorted = notebooks.sortWith(comp)
    var max = sorted(0)._2
    for (i <- 1 until n) {
      if (sorted(i)._2 > max) {
        out.println("Happy Alex")
        return 1
      }
      max = Math.max(max, sorted(i)._2)
    }
    out.println("Poor Alex")
    return 1
  }

  def main(args: Array[String]): Unit = {
    br = new BufferedReader(new InputStreamReader(System.in))
    out = new PrintWriter(new BufferedOutputStream(System.out))
    solve
    out.close
  }
}

import java.util.Scanner

import scala.collection.mutable.ArrayBuffer

/**
 * Created by Kuang.Ru on 14-10-11.
 */
object A456 {
  def main(args: Array[String]) {
    val sc = new Scanner(System.in)
    val n = sc.nextInt()
    var i = 0
    val laptops = new ArrayBuffer[(Int, Int)]()

    while (i < n) {
      val a, b = sc.nextInt()
      laptops.append((a, b))
      i += 1
    }

    laptops.sorted
    i = 1

    while (i < n) {
      if (laptops(i - 1)._2 > laptops(i)._2) {
        println("Happy Alex")
        return
      }

      i += 1
    }

    println("Poor Alex")
  }
}

import scala.io.Source;

object CF_456_A extends App {
  override def main(args: Array[String]) {
    val stream = Source.fromInputStream(System.in)
    val lines = stream.getLines().toList
    val n = lines.head.toInt
    val arr = lines.map(s => {s.split("[ ]+").map(_.toInt)}).filter(a => a.length > 1).map(arr => (arr(0), arr(1))).toArray

    arr.sorted

    def calc:Boolean = {
      for (i <- 0 until arr.length - 1)
        if ((arr(i)._1 != arr(i + 1)._1) && (arr(i)._2 > arr(i + 1)._2))
          return true
      false
    }
      if (calc) println("Happy Alex") else println("Poor Alex")
  }
}


After a hard-working week Polycarp prefers to have fun. Polycarp's favorite entertainment is drawing snakes. He takes a rectangular checkered sheet of paper of size $$$n \times m$$$ (where $$$n$$$ is the number of rows, $$$m$$$ is the number of columns) and starts to draw snakes in cells.Polycarp draws snakes with lowercase Latin letters. He always draws the first snake with the symbol 'a', the second snake with the symbol 'b', the third snake with the symbol 'c' and so on. All snakes have their own unique symbol. There are only $$$26$$$ letters in the Latin alphabet, Polycarp is very tired and he doesn't want to invent new symbols, so the total number of drawn snakes doesn't exceed $$$26$$$.Since by the end of the week Polycarp is very tired, he draws snakes as straight lines without bends. So each snake is positioned either vertically or horizontally. Width of any snake equals $$$1$$$, i.e. each snake has size either $$$1 \times l$$$ or $$$l \times 1$$$, where $$$l$$$ is snake's length. Note that snakes can't bend.When Polycarp draws a new snake, he can use already occupied cells for drawing the snake. In this situation, he draws the snake "over the top" and overwrites the previous value in the cell.Recently when Polycarp was at work he found a checkered sheet of paper with Latin letters. He wants to know if it is possible to get this sheet of paper from an empty sheet by drawing some snakes according to the rules described above. If it is possible, he is interested in a way to draw snakes.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 10^5$$$) — the number of test cases to solve. Then $$$t$$$ test cases follow. The first line of the test case description contains two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 2000$$$) — length and width of the checkered sheet of paper respectively. Next $$$n$$$ lines of test case description contain $$$m$$$ symbols, which are responsible for the content of the corresponding cell on the sheet. It can be either lowercase Latin letter or symbol dot ('.'), which stands for an empty cell. It is guaranteed that the total area of all sheets in one test doesn't exceed $$$4\cdot10^6$$$.

Print the answer for each test case in the input. In the first line of the output for a test case print YES if it is possible to draw snakes, so that you can get a sheet of paper from the input. If it is impossible, print NO. If the answer to this question is positive, then print the way to draw snakes in the following format. In the next line print one integer $$$k$$$ ($$$0 \le k \le 26$$$) — number of snakes. Then print $$$k$$$ lines, in each line print four integers $$$r_{1,i}$$$, $$$c_{1,i}$$$, $$$r_{2,i}$$$ and $$$c_{2,i}$$$ — coordinates of extreme cells for the $$$i$$$-th snake ($$$1 \le r_{1,i}, r_{2,i} \le n$$$, $$$1 \le c_{1,i}, c_{2,i} \le m$$$). Snakes should be printed in order of their drawing. If there are multiple solutions, you are allowed to print any of them. Note that Polycarp starts drawing of snakes with an empty sheet of paper.

object Main {
  import java.io.{BufferedReader, InputStream, InputStreamReader}
  import java.util.StringTokenizer
  import scala.reflect.ClassTag

  def main(args: Array[String]): Unit = {
    val out = new java.io.PrintWriter(System.out)
    new Main(out, new InputReader(System.in)).solve()
    out.flush()
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null
  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  def debugDimFlip(m: Array[Array[Long]]): Unit = if (!oj){
    REP(m(0).length) { j =>
      REP(m.length) { i =>
        System.err.print(m(i)(j))
        System.err.print(" ")
      }
      System.err.println()
    }
  }
  def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  def debugL(num: => Long): Unit = DEBUG {
    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 = 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) { i =>
      f(i)
    }
  }
  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[Int] = {
    val cum = Array.ofDim[Int](as.length + 1)
    REP(as.length) { i =>
      cum(i + 1) = cum(i) + as(i)
    }
    cum
  }
}

class Main(out: java.io.PrintWriter, sc: Main.InputReader) {
  import sc._
  import Main._
  import java.util.Arrays.sort

  import scala.collection.mutable
  import math.{abs, max, min}
  import mutable.ArrayBuffer

  // toIntとか+7とかするならvalにしろ
  @inline private def MOD = 1000000007

  class Axis {
    def set(v: Int, i: Int): Unit = {
      if (empty) {
        ok = true
        this.v = v
      } else if (this.v != v) {
        ok = false
      }
      ms = min(ms, i)
      mx = max(mx, i)
    }

    def empty: Boolean = v == -1

    def reset(): Unit = {
      ok = false
      v = -1
      ms = 1e4.toInt
      mx = 0
    }

    var ok: Boolean = false
    var v: Int = 0
    var ms: Int = 0
    var mx: Int = 0

    override def toString: String = s"ok:$ok v:$v ms:$ms mx:$mx"

    def answer = Answer(v + 1, ms + 1, v + 1, mx + 1)
  }

  case class Answer(r1: Int, c1: Int, r2: Int, c2: Int) {
    def rotate: Answer = Answer(c1, r1, c2, r2)
  }

  val H, V = Array.fill[Axis](26)(new Axis)

  def solve2(): Boolean = {
    REP(26) { i =>
      H(i).reset()
      V(i).reset()
    }
    val N, M = ni()
    val g = nm_c(N, M)
    REP(N) { i =>
      REP(M) { j =>
        if (g(i)(j) != '.') {
          val c = g(i)(j) - 'a'
          H(c).set(i, j)
          V(c).set(j, i)
        }
      }
    }

    DEBUG {
      debug("H")
      H.foreach(a => debug(a.toString))
      debug("V")
      V.foreach(a => debug(a.toString))
    }

    def test(c: Int, ax: Axis)(f: Int => Char): Boolean = {
      TO(ax.ms, ax.mx) { i =>
        val c2 = f(i)
        if (c2 == '.' || c2 - 'a' < c) return false
      }
      true
    }

    var ok = true
    REP(26) { i =>
      // 出てこない OR どっちかの軸が正解
      ok &&= H(i).empty ||
        (H(i).ok && test(i, H(i))(g(H(i).v)(_))) ||
        (V(i).ok && test(i, V(i))(g(_)(V(i).v)))
    }
    if (!ok) return false

    out.println("YES")
    var last = -1
    REP(26) { i =>
      // チェック済みなので、この時点ではokかどうかだけでいい
      if (H(i).ok || V(i).ok) last = i
    }
    out.println(last + 1)
    REP(last + 1) { i =>
      val ix = if (H(i).ok || V(i).ok) i else last // 上書きされる蛇は最後の文字と同じ線にしておく
      val ans = if (H(ix).ok) H(ix).answer else V(ix).answer.rotate
      out.println(s"${ans.r1} ${ans.c1} ${ans.r2} ${ans.c2}")
    }

    true
  }

  def solve(): Unit = {
    REP(ni()) { _ =>
      // 失敗のときだけこっちで出力する
      if (!solve2()) {
        out.println("NO")
      }
    }
  }
}


A string is called palindrome if it reads the same from left to right and from right to left. For example "kazak", "oo", "r" and "mikhailrubinchikkihcniburliahkim" are palindroms, but strings "abb" and "ij" are not.You are given string s consisting of lowercase Latin letters. At once you can choose any position in the string and change letter in that position to any other lowercase letter. So after each changing the length of the string doesn't change. At first you can change some letters in s. Then you can permute the order of letters as you want. Permutation doesn't count as changes. You should obtain palindrome with the minimal number of changes. If there are several ways to do that you should get the lexicographically (alphabetically) smallest palindrome. So firstly you should minimize the number of changes and then minimize the palindrome lexicographically.

The only line contains string s (1 ≤ |s| ≤ 2·105) consisting of only lowercase Latin letters.

Print the lexicographically smallest palindrome that can be obtained with the minimal number of changes.

/**
 * Created by katerinaglushchenko on 9/18/16.
 */
object Task3 {
  def main(args: Array[String]) {
    val str = readLine()
    val sorted = str.sorted
    val notHasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 1) Some(s._2.head) else None).toList.sorted
    val hasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 0) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else if (s._2.length >= 3) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else None).flatten.toList
    val rest = notHasPair.take(notHasPair.size / 2)
    val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else ""
    val half = (hasPair ++ rest).sorted
    println((half ++ center ++ half.reverse).mkString(""))
  }
}

object Task3 {
  def main(args: Array[String]) {
    val str = readLine()
    val p = str.sorted.zipWithIndex.partition(_._2 % 2 == 0)
    val p1 = p._1.map(_._1)
    val p2 = p._2.map(_._1)

    val sorted = str.sorted
    val hasPair = sorted.zipWithIndex.flatMap(s => if (s._2 + 1 < sorted.length && sorted.charAt(s._2 + 1) == s._1) Some(s._1) else None)
    val notHasPair = sorted.toCharArray.toSet -- hasPair.toSet

    val p11 = hasPair
    val p22 = hasPair

    val center = if(notHasPair.size%2==1) notHasPair.toList(notHasPair.size/2).toString else ""
    val rest = if(notHasPair.size%2==1) notHasPair - center.head else notHasPair
    val gr = rest.grouped(2).toList.map(s=>s.head)

    println((p11++gr++center.toCharArray++gr++p22.reverse).mkString(""))
  }
}

/**
 * Created by katerinaglushchenko on 9/18/16.
 */
object Task3 {
  def main(args: Array[String]) {
    val str = readLine()
    if(isPalindrom(str))
      println(str)
    else {
      val p = str.sorted.zipWithIndex.partition(_._2 % 2 == 0)

      val sorted = str.sorted
      val hasPair = sorted.zipWithIndex.flatMap(s => if (s._2 + 1 < sorted.length && sorted.charAt(s._2 + 1) == s._1) Some(s._1) else None)
      val notHasPair = sorted.toCharArray.toSet -- hasPair.toSet

      val p11 = hasPair
      val p22 = hasPair

      val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else ""
      val rest = if (notHasPair.size % 2 == 1) notHasPair - center.head else notHasPair
      println("center " + center)
      val gr = rest.grouped(2).toList.map(s => s.head)
      gr.foreach(r => println(r))

      println((p11 ++ gr ++ center.toCharArray ++ gr ++ p22.reverse).mkString(""))
    }
  }

  def isPalindrom(str: String) = {
    val center1 = str.length / 2
    val center2 = if ((str.length % 2) == 1) (str.length / 2) + 1 else str.length / 2
    val parts = List(str.substring(0, center1), str.substring(center2, str.length))
    parts(0) == parts(1).reverse
  }
}

object Task3 {
  def main(args: Array[String]) {
    val str = readLine()
    val sorted = str.sorted
    val notHasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 1) Some(s._2.head) else None).toList
    val hasPair = sorted.groupBy(i => i).flatMap(s => if (s._2.length % 2 == 0) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else if (s._2.length >= 3) Some((s._2.head.toString * (s._2.length / 2)).toCharArray) else None).flatten.toList
    val rest = notHasPair.take(notHasPair.size / 2)
    val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else ""
    val half = (hasPair ++ rest).sorted
    println((half ++ center ++ half.reverse).mkString(""))
  }
}

object Task3 {
  def main(args: Array[String]) {
    val str = readLine()
    if(isPalindrom(str))
      println(str)
    else {
      val p = str.sorted.zipWithIndex.partition(_._2 % 2 == 0)

      val sorted = str.sorted
      val hasPair = sorted.zipWithIndex.flatMap(s => if (s._2 + 1 < sorted.length && sorted.charAt(s._2 + 1) == s._1) Some(s._1) else None)
      val notHasPair = sorted.toCharArray.toSet -- hasPair.toSet

      val p11 = hasPair
      val p22 = hasPair

      val center = if (notHasPair.size % 2 == 1) notHasPair.toList(notHasPair.size / 2).toString else ""
      val rest = if (notHasPair.size % 2 == 1) notHasPair - center.head else notHasPair
      val gr = rest.grouped(2).toList.map(s => s.head)

      println((p11 ++ gr ++ center.toCharArray ++ gr ++ p22.reverse).mkString(""))
    }
  }

  def isPalindrom(str: String) = {
    val center1 = str.length / 2
    val center2 = if ((str.length % 2) == 1) (str.length / 2) + 1 else str.length / 2
    val parts = List(str.substring(0, center1), str.substring(center2, str.length))
    parts(0) == parts(1).reverse
  }
}


A Martian boy is named s — he has got this name quite recently from his parents for his coming of age birthday. Now he enjoys looking for his name everywhere. If he sees that he can obtain his name from some string by removing zero or more letters (at that, the remaining letters remain in the same order), he gets happy. For example, if s=«aba», then strings «baobab», «aabbaa», «helloabahello» make him very happy and strings «aab», «baaa» and «helloabhello» do not.However rather than being happy once, he loves twice as much being happy twice! So, when he got string t as a present, he wanted to cut it in two parts (the left part and the right part) so that each part made him happy.Help s determine the number of distinct ways to cut the given string t into two parts in the required manner.

The first line contains string s, consisting of lowercase English letters. The length of string s is from 1 to 1000 letters. The second line contains string t, that also consists of lowercase English letters. The length of string t is from 1 to 106 letters.

Print the sought number of ways to cut string t in two so that each part made s happy.

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val name = in.next()
  val reverse = name.reverse
  val line = in.next()
  val (index, _) = line.indices.foldLeft(-1, 0) {
    case(acc@(-1, i), el) if name(i) == line(el) => {
      if (i == name.length - 1)
        (el, i)
      else
        (-1, i + 1)
    }
    case (acc, el) => acc
  }
  val (index2, _) = line.indices.reverse.foldLeft(-1, 0) {
    case(acc@(-1, i), el) if reverse(i) == line(el) => {
      if (i == name.length - 1)
        (el, i)
      else
        (-1, i + 1)
    }
    case (acc, el) => acc
  }

  if (index == -1 || index2 == -1 || (index >= index2))
    println(0)
  else
    println(index2 - index)
}

object Main extends App {
import scala.collection.JavaConversions._
import java.util.Scanner

    val scanner = new Scanner(System.in)
    val s = scanner.nextLine().toCharArray()
    val t = scanner.nextLine().toCharArray()
    scanner.close()
    val bestFirstEnd = findFromStart(s, t)
    val bestSecondStart = findFromEnd(s, t)
    val ans = Math.max(0, bestSecondStart - bestFirstEnd)
    println(ans)

  private def findFromStart(s: Array[Char], t: Array[Char]): Int = {
    val len = t.length
    var checkIndex = 0
    for (i <- 0 until len if s(checkIndex) == t(i)) {
      checkIndex += 1
      if (checkIndex == s.length) {
        return i
      }
    }
    t.length
  }

  private def findFromEnd(s: Array[Char], t: Array[Char]): Int = {
    var checkIndex = s.length - 1
    var i = t.length - 1
    while (i >= 0) {
      if (s(checkIndex) == t(i)) {
        checkIndex -= 1
        if (checkIndex < 0) {
          return i
        }
      }
      i -= 1
    }
    0
}
}

object C523 extends App{

  val t  = readLine
  val tL, tR = new Array[Byte](t.length)
  val s  = readLine
  val sr = s.reverse
  val tlen = tL.length

  def returnIdx(tArr : Array[Byte], s : String, t : String) = {
    var idx = 0
    val it = s.iterator
    var l = 0

    while(it.hasNext && idx <= (tlen - 1)) {
      val i = it.next
      l += 1
      if ((t(idx) == i) && tArr(idx) == 0) {
        tArr(idx) = 1
        idx += 1
      }
    }

    l
  }

  val iL = returnIdx(tL, s, t ) - 1
  val iR = s.length - returnIdx(tR, sr, t.reverse) - 1

  println(if(iR - iL + 1 <= 0) 0 else iR - iL + 1)
}

object C523 extends App{

  private final val t  = readLine
  private final val tL, tR = new Array[Byte](t.length)
  private final val s  = readLine
  private final val sr = s.reverse
  private final val tlen = tL.length

  def returnIdx(tArr : Array[Byte], s : String, t : String) = {
    var idx = 0
    val it = s.iterator
    var l = 0

    while(it.hasNext && idx <= (tlen - 1)) {
      val i = it.next
      l += 1
      if ((t(idx) == i) && tArr(idx) == 0) {
        tArr(idx) = 1
        idx += 1
      }
    }

    l
  }

  val iL = returnIdx(tL, s, t ) - 1
  val iR = s.length - returnIdx(tR, sr, t.reverse) - 1

  println(if(iR - iL + 1 <= 0) 0 else iR - iL + 1)

}

object Main extends App {
import java.util.Scanner
import scala.collection.JavaConversions._
val input = new Scanner(System.in)
val s = input.next()
val t = input.next()
val stop = false
var pos_s = 0
var pos_1 = -1
var pos_2 = -1
val found = false
for (i <- 0 until t.length if t.charAt(i) == s.charAt(pos_s)) {
  if (pos_s == s.length - 1) {
    pos_1 = i
    //break
  } else pos_s += 1
}
if (pos_1 > -1) {
  var i = t.length - 1
  while (i > pos_1) {
    if (t.charAt(i) == s.charAt(pos_s)) {
      if (pos_s == 0) {
        pos_2 = i
        //break
      } else pos_s -= 1
    }
    i -= 1
  }
}
if (pos_1 == -1) println(0) else {
  if (pos_2 == -1) println(0) else println(pos_2 - pos_1)
}
input.close()
}

object C523 extends App{

  val t  = readLine
  val tL, tR = new Array[Byte](t.length)
  val s  = readLine
  val sr = s.reverse
  val tlen = tL.length

  def returnIdx(tArr : Array[Byte], s : String) = {
    var idx = 0
    val it = s.iterator
    var l = 0

    while(it.hasNext && idx <= (tlen - 1)) {
      val i = it.next
      l += 1
      if ((t(idx) == i) && tArr(idx) == 0) {
        tArr(idx) = 1
        idx += 1
      }
    }

    l
  }

  val iL = returnIdx(tL, s) - 1
  val iR = s.length - returnIdx(tR, sr) - 1

  println(if(iR - iL + 1 <= 0) 0 else iR - iL + 1)
}


Bob is playing a game named "Walk on Matrix".In this game, player is given an $$$n \times m$$$ matrix $$$A=(a_{i,j})$$$, i.e. the element in the $$$i$$$-th row in the $$$j$$$-th column is $$$a_{i,j}$$$. Initially, player is located at position $$$(1,1)$$$ with score $$$a_{1,1}$$$. To reach the goal, position $$$(n,m)$$$, player can move right or down, i.e. move from $$$(x,y)$$$ to $$$(x,y+1)$$$ or $$$(x+1,y)$$$, as long as player is still on the matrix.However, each move changes player's score to the bitwise AND of the current score and the value at the position he moves to.Bob can't wait to find out the maximum score he can get using the tool he recently learnt  — dynamic programming. Here is his algorithm for this problem.   However, he suddenly realize that the algorithm above fails to output the maximum score for some matrix $$$A$$$. Thus, for any given non-negative integer $$$k$$$, he wants to find out an $$$n \times m$$$ matrix $$$A=(a_{i,j})$$$ such that   $$$1 \le n,m \le 500$$$ (as Bob hates large matrix);  $$$0 \le a_{i,j} \le 3 \cdot 10^5$$$ for all $$$1 \le i\le n,1 \le j\le m$$$ (as Bob hates large numbers);  the difference between the maximum score he can get and the output of his algorithm is exactly $$$k$$$. It can be shown that for any given integer $$$k$$$ such that $$$0 \le k \le 10^5$$$, there exists a matrix satisfying the above constraints.Please help him with it!

The only line of the input contains one single integer $$$k$$$ ($$$0 \le k \le 10^5$$$).

Output two integers $$$n$$$, $$$m$$$ ($$$1 \le n,m \le 500$$$) in the first line, representing the size of the matrix.  Then output $$$n$$$ lines with $$$m$$$ integers in each line, $$$a_{i,j}$$$ in the $$$(i+1)$$$-th row, $$$j$$$-th column.

NoteIn the first example, the maximum score Bob can achieve is $$$300000$$$, while the output of his algorithm is $$$300000$$$.In the second example, the maximum score Bob can achieve is $$$7\&3\&3\&3\&7\&3=3$$$, while the output of his algorithm is $$$2$$$.

object D extends App {
  val k = scala.io.StdIn.readInt()
  val a = 1 << 17

  println("2 3")
  println(s"${a ^ k} $a 0")
  println(s"$k ${a ^ k} $k")
}


You are given an undirected weighted connected graph with $$$n$$$ vertices and $$$m$$$ edges without loops and multiple edges.The $$$i$$$-th edge is $$$e_i = (u_i, v_i, w_i)$$$; the distance between vertices $$$u_i$$$ and $$$v_i$$$ along the edge $$$e_i$$$ is $$$w_i$$$ ($$$1 \le w_i$$$). The graph is connected, i. e. for any pair of vertices, there is at least one path between them consisting only of edges of the given graph.A minimum spanning tree (MST) in case of positive weights is a subset of the edges of a connected weighted undirected graph that connects all the vertices together and has minimum total cost among all such subsets (total cost is the sum of costs of chosen edges).You can modify the given graph. The only operation you can perform is the following: increase the weight of some edge by $$$1$$$. You can increase the weight of each edge multiple (possibly, zero) times.Suppose that the initial MST cost is $$$k$$$. Your problem is to increase weights of some edges with minimum possible number of operations in such a way that the cost of MST in the obtained graph remains $$$k$$$, but MST is unique (it means that there is only one way to choose MST in the obtained graph).Your problem is to calculate the minimum number of operations required to do it.

The first line of the input contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 2 \cdot 10^5, n - 1 \le m \le 2 \cdot 10^5$$$) — the number of vertices and the number of edges in the initial graph. The next $$$m$$$ lines contain three integers each. The $$$i$$$-th line contains the description of the $$$i$$$-th edge $$$e_i$$$. It is denoted by three integers $$$u_i, v_i$$$ and $$$w_i$$$ ($$$1 \le u_i, v_i \le n, u_i \ne v_i, 1 \le w \le 10^9$$$), where $$$u_i$$$ and $$$v_i$$$ are vertices connected by the $$$i$$$-th edge and $$$w_i$$$ is the weight of this edge. It is guaranteed that the given graph doesn't contain loops and multiple edges (i.e. for each $$$i$$$ from $$$1$$$ to $$$m$$$ $$$u_i \ne v_i$$$ and for each unordered pair of vertices $$$(u, v)$$$ there is at most one edge connecting this pair of vertices). It is also guaranteed that the given graph is connected.

Print one integer — the minimum number of operations to unify MST of the initial graph without changing the cost of MST.

NoteThe picture corresponding to the first example: You can, for example, increase weight of the edge $$$(1, 6)$$$ or $$$(6, 3)$$$ by $$$1$$$ to unify MST.The picture corresponding to the last example: You can, for example, increase weights of edges $$$(1, 5)$$$ and $$$(2, 4)$$$ by $$$1$$$ to unify MST.

object Main extends App {

  import java.io._
import java.util
import java.util.{Locale, StringTokenizer, TreeSet}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val m = in.nextInt

  case class Edge(u: Int, v: Int, w: Int, var taked: Boolean = false)
  var edges = new Array[Edge](m+1)

  for (i <- 0 until m) {
    edges(i) = Edge(in.nextInt - 1, in.nextInt - 1, in.nextInt)
  }

  edges(m) = Edge(0, 0, Int.MaxValue)
  edges = edges.sortBy(_.w)

  val max = new Array[Int](n)
  val taked = new Array[Boolean](m)
  val dsu = new DSU(n)
  var sum = 0
  var cnt = 0

  var set = new mutable.TreeSet[(Int, Int, Int)]

  var prevw = -1
  for (e <- edges) {

    if (e.w != prevw) {
      for ((x, y, z) <- set)
        if (dsu.get(x) != dsu.get(y)) {
          dsu.union(x, y)
          sum += z
        }
        else {
          cnt += 1
        }
      set = new mutable.TreeSet[(Int, Int, Int)]
      prevw = e.w
    }

    if (dsu.get(e.u) != dsu.get(e.v)) {
      val x = dsu.get(e.u)
      val y = dsu.get(e.v)
      //System.err.println(x + " " + y + " " + e.w)
      val t = (x min y, x max y, e.w)
      if (set contains t)
        cnt += 1
      else
        set.add(t)
    }
  }

  //System.err.println(sum)

  out.print(cnt)

  out.flush()
  out.close()

  class DSU(n: Int) {
    val set = new Array[Int](n).zipWithIndex.map(p => p._2)

    def get(a: Int): Int = {
      if (set(a) == a)
        a
      else {
        set(a) = get(set(a))
        set(a)
      }
    }

    def union(a: Int, b: Int): Unit = {
      val x = get(a)
      val y = get(b)
      if (x != y) set(x) = y;
    }

  }

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}

object Main2 extends App {

  import java.io._
import java.util
import java.util.{Locale, StringTokenizer, TreeSet}

import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.io.StdIn

  val in = new Reader()
  val out: PrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))

  val MOD = 1000000000 + 7
  val eps = 0.00000001

  val n = in.nextInt
  val m = in.nextInt

  case class Edge(u: Int, v: Int, w: Int, var taked: Boolean = false)
  var edges = new Array[Edge](m+1)

  for (i <- 0 until m) {
    edges(i) = Edge(in.nextInt - 1, in.nextInt - 1, in.nextInt)
  }

  edges(m) = Edge(0, 0, Int.MaxValue)
  edges = edges.sortBy(_.w)

  val max = new Array[Int](n)
  val taked = new Array[Boolean](m)
  val dsu = new DSU(n)
  var sum = 0
  var cnt = 0

  var set = new mutable.TreeSet[(Int, Int, Int)]

  var prevw = -1
  for (e <- edges) {

    if (e.w != prevw) {
      for ((x, y, z) <- set)
        if (dsu.get(x) != dsu.get(y)) {
          dsu.union(x, y)
          sum += z
        }
        else {
          cnt += 1
        }
      set = new mutable.TreeSet[(Int, Int, Int)]
      prevw = e.w
    }

    if (dsu.get(e.u) != dsu.get(e.v)) {
      val x = e.u
      val y = e.v
      //System.err.println(x + " " + y + " " + e.w)
      val t = (x, y, e.w)
      set.add(t)
    }
  }

  //System.err.println(sum)

  out.print(cnt)

  out.flush()
  out.close()

  class DSU(n: Int) {
    val set = new Array[Int](n).zipWithIndex.map(p => p._2)

    def get(a: Int): Int = {
      if (set(a) == a)
        a
      else {
        set(a) = get(set(a))
        set(a)
      }
    }

    def union(a: Int, b: Int): Unit = {
      val x = get(a)
      val y = get(b)
      if (x != y) set(x) = y;
    }

  }

  class Reader @throws[IOException]
  () {
    var br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
    var tok: StringTokenizer = null

    def this(file: String) {
      this()
      br = new BufferedReader(new FileReader(file))
    }

    @throws[IOException]
    def next: String = {
      while (tok == null || !tok.hasMoreElements) tok = new StringTokenizer(br.readLine)
      tok.nextToken
    }

    @throws[NumberFormatException]
    @throws[IOException]
    def nextInt: Int = Integer.valueOf(next)

    @throws[NumberFormatException]
    @throws[IOException]
    def nextLong: Long = next.toLong

    @throws[NumberFormatException]
    @throws[IOException]
    def nextDouble: Double = next.toDouble

    @throws[IOException]
    def nextLine: String = br.readLine
  }

}


Jett is tired after destroying the town and she wants to have a rest. She likes high places, that's why for having a rest she wants to get high and she decided to craft staircases.A staircase is a squared figure that consists of square cells. Each staircase consists of an arbitrary number of stairs. If a staircase has $$$n$$$ stairs, then it is made of $$$n$$$ columns, the first column is $$$1$$$ cell high, the second column is $$$2$$$ cells high, $$$\ldots$$$, the $$$n$$$-th column if $$$n$$$ cells high. The lowest cells of all stairs must be in the same row.A staircase with $$$n$$$ stairs is called nice, if it may be covered by $$$n$$$ disjoint squares made of cells. All squares should fully consist of cells of a staircase. This is how a nice covered staircase with $$$7$$$ stairs looks like:  Find out the maximal number of different nice staircases, that can be built, using no more than $$$x$$$ cells, in total. No cell can be used more than once.

The first line contains a single integer $$$t$$$ $$$(1 \le t \le 1000)$$$  — the number of test cases. The description of each test case contains a single integer $$$x$$$ $$$(1 \le x \le 10^{18})$$$  — the number of cells for building staircases.

For each test case output a single integer  — the number of different nice staircases, that can be built, using not more than $$$x$$$ cells, in total.

NoteIn the first test case, it is possible to build only one staircase, that consists of $$$1$$$ stair. It's nice. That's why the answer is $$$1$$$.In the second test case, it is possible to build two different nice staircases: one consists of $$$1$$$ stair, and another consists of $$$3$$$ stairs. This will cost $$$7$$$ cells. In this case, there is one cell left, but it is not possible to use it for building any nice staircases, that have not been built yet. That's why the answer is $$$2$$$.In the third test case, it is possible to build only one of two nice staircases: with $$$1$$$ stair or with $$$3$$$ stairs. In the first case, there will be $$$5$$$ cells left, that may be used only to build a staircase with $$$2$$$ stairs. This staircase is not nice, and Jett only builds nice staircases. That's why in this case the answer is $$$1$$$. If Jett builds a staircase with $$$3$$$ stairs, then there are no more cells left, so the answer is $$$1$$$ again.

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

import scala.annotation.tailrec

object B {
  def solve(in: Input, out: PrintWriter): Unit = {
    val ladders = new Array[Long](31)
    ladders(0) = 1
    for (i <- 1 until ladders.length) {
      ladders(i) = (1L << (2 * i)) + 2 * ladders(i - 1)
    }

    for (_ <- 0 until in.nextInt()) {
      var z = in.nextLong()
      var i = 0
      while (i < ladders.length && ladders(i) <= z) {
        z -= ladders(i)
        i += 1
      }
      out.println(i)
    }
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("4\n1\n8\n6\n1000000000000000000", "1\n2\n1\n30", "Sample")
  )

  def main(args: Array[String]): Unit = {
    if (args.length == 0) {
      val input = new Input(new InputStreamReader(System.in))
      val output = new PrintWriter(System.out)
      solve(input, output)
      output.close()
      input.close()
    } else {
      for ((in, ans, name) <- makeTests()) {
        val input = new Input(new StringReader(in))
        val output = new StringWriter()
        val pwOutput = new PrintWriter(output)
        val t0 = System.nanoTime()
        solve(input, pwOutput)
        val time = System.nanoTime() - t0
        pwOutput.close()
        output.close()
        val result = output.toString
        if (ans.trim != result.trim) {
          throw new RuntimeException(s"Test '$name': expected '$ans' found '$result'")
        } else {
          println(s"Test '$name' was solved in ${time / 1e9} seconds")
        }
      }
    }
  }

  class Input(stream: Reader) extends Closeable {
    private[this] val reader = new BufferedReader(stream)
    private[this] var tokenizer = new StringTokenizer(reader.readLine())

    @tailrec
    final def nextToken(): String = if (tokenizer.hasMoreTokens) tokenizer.nextToken() else {
      tokenizer = new StringTokenizer(reader.readLine())
      nextToken()
    }

    def nextInt(): Int = nextToken().toInt
    def nextLong(): Long = nextToken().toLong
    def nextDouble(): Double = nextToken().toDouble

    override def close(): Unit = reader.close()
  }
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val x = readLong()

    @annotation.tailrec
    def go(x: Long, n: Long, count: Int): Int = {
      val req = n * (n + 1) / 2

      if (x - req >= 0) go(x - req, n + n + 1, count + 1)
      else count
    }

    val ans = go(x, 1, 0)

    println(ans)
  }
}