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, 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-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);
    }
  }
}


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.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 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")
  }
}


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 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 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)
}


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
  }

}


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)
  }
}


import io.Source
import java.io.PrintWriter

object CF292E {

  def solve(in: In, out: PrintWriter) {
    val n, m = in().toInt
    val a = Array.fill(n)(in().toInt)
    val b = Array.fill(n)(in().toInt)
    val size = {
      var k = 1
      while (k < n) {
        k *= 2
      }
      k
    }
    val offset = Array.fill(size + n - 1)(-1)
    def update(n: Int, nl: Int, nr: Int, l: Int, r: Int, v: Int) {
      if (l <= nl && nr <= r) {
        offset(n) = v + nl - l
      } else if (r > nl && nr > l) {
        if (offset(n) != -1) {
          offset(2 * n + 1) = offset(n)
          offset(2 * n + 2) = offset(n) + (nr - nl) / 2
          offset(n) = -1
        }
        val mid = (nl + nr) / 2
        update(2 * n + 1, nl, mid, l, r, v)
        update(2 * n + 2, mid, nr, l, r, v)
      }
    }
    def get(n: Int, nl: Int, nr: Int, i: Int): Int = {
      if (offset(n) != -1) {
        a(offset(n) + (i - nl))
      } else if (nl + 1 == nr) {
        b(i)
      } else {
        val mid = (nl + nr) / 2
        if (i < mid) {
          get(2 * n + 1, nl, mid, i)
        } else {
          get(2 * n + 2, mid, nr, i)
        }
      }
    }
    for (it <- 0 until m) {
      if (in().toInt == 1) {
        val x, y = in().toInt - 1
        val k = in().toInt
        update(0, 0, size, y, y + k, x)
        //out.println(offset.deep)
      } else {
        out.println(get(0, 0, size, in().toInt - 1))
      }
    }
  }

  def main(args: Array[String]) {
    val in: In = new In(Source.fromInputStream(System.in))
    val out: PrintWriter = new PrintWriter(System.out)
    solve(in, out)
    out.close()
  }

  class TokenIterator(iter: BufferedIterator[Char], delims: String) extends Iterator[String] {
    private val sb = new StringBuilder

    def hasNext: Boolean = {
      skipDelims()
      iter.hasNext
    }

    def skipDelims() {
      while (iter.hasNext && delims.indexOf(iter.head) != -1) {
        iter.next()
      }
    }

    def next(): String = {
      skipDelims()
      while (iter.hasNext && delims.indexOf(iter.head) == -1) {
        sb.append(iter.next())
      }
      val ret = sb.toString()
      sb.clear()
      ret
    }
  }

  class In(source: Source) {
    val iter = source.buffered

    val tokenIterator = new TokenIterator(iter, " \r\n")

    val lineIterator = new TokenIterator(iter, "\r\n")

    def apply() = tokenIterator.next()

    def apply(n: Int) = tokenIterator.take(n)
  }
}

/*
E. Копирование данных
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Очень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.

Более формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:

    Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.
    Определить значение в позиции x массива b, то есть найти значение bx.

Для каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.
Входные данные

В первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).

В следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.

Все числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.
Выходные данные

Для каждого запроса второго типа в отдельную строку выведите результат.
Примеры тестов
Входные данные

5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2

Выходные данные

0
3
-1
3
2
3
-1
*/
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

object CrocRound1Task5 extends App {

  def solve(a: Array[Long], b: IndexedSeq[Long], actions: Seq[Action]): Seq[Long] = {
    //    val now = System.currentTimeMillis
    val tree = MutableSegmentTree.fromSeq(b)
    //    println("tree built in " + (System.currentTimeMillis - now))
    solve(a, tree, actions)
  }

  def solve(a: Array[Long], tree: MutableSegmentTree[Long], actions: Seq[Action]): Seq[Long] = {
    val toPrint = ArrayBuffer.empty[Long]
    actions foreach (action => action match {
      case c: Copy => tree.updateRange(c.posB - 1, c.posB + c.length - 2)(i => a(i - c.posB + c.posA))
      case Find(p) => toPrint += tree(p - 1)
    })
    toPrint
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val a = readLine split ' ' map (_.toLong)
  val b = readLine split ' ' map (_.toLong)
  val actions: IndexedSeq[Action] = (0 until m) map { _ =>
    val s = readLine split ' ' map (_.toInt)
    if (s(0) == 1) Copy(s(1), s(2), s(3))
    else Find(s(1))
  }
  val res = solve(a, b, actions)
  res foreach (x => println(x))
}

abstract class Action {}

case class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}

case class Find(val pos: Int) extends Action {}

// SegmentTree impl copy-paste
abstract class MutableSegmentTree[T] {
  def range = start to end
  def size = end - start + 1
  def start: Int
  def end: Int

  def apply(i: Int): T
  def left: Option[MutableSegmentTree[T]]
  def right: Option[MutableSegmentTree[T]]
  def updateRange(lb: Int, rb: Int)(f: Int => T): Unit
  def update(f: Int => T): Unit
}

object MutableSegmentTree {

  def fromSeq[T](data: IndexedSeq[T]): MutableSegmentTree[T] = {
    def formTreeRec(nodes: Seq[MutableSegmentTree[T]]): MutableSegmentTree[T] = {
      if (nodes.size == 1) nodes.head
      else {
        // Optimized, doesn't use grouped(2)
        val united = for (i <- 0 until nodes.size by 2) yield {
          if (i == nodes.size - 1) SegNode(nodes(i))
          else SegNode(nodes(i), nodes(i + 1))
        }
        formTreeRec(united)
      }
    }
    val leaves = (0 until data.size) map (i => leaf(i, data(i)))
    formTreeRec(leaves)
  }

  private def leaf[T](i: Int, d: T) = new SegLeaf(i, d)
}

class SegNode[T](val l: MutableSegmentTree[T],
                 val r: Option[MutableSegmentTree[T]],
                 val start: Int,
                 val end: Int,
                 var func: Option[Int => T]) extends MutableSegmentTree[T] {
  def left = Some(l)
  def right = r

  def hasRightBranch = r.isDefined

  def apply(i: Int): T = {
    require(i >= start && i <= end, "index is out of bounds")
    if (func.isDefined) {
      (func.get)(i)
    } else if (i >= l.start && i <= l.end) {
      l(i)
    } else {
      (r.get)(i)
    }
  }

  def updateRange(lb: Int, rb: Int)(f: Int => T): Unit = {
    if (within(start, end, lb, rb)) {
      update(f)
    } else if (intersects(start, end, lb, rb)) {
      // Optimized routine
      if (func.isDefined) {
        val f2 = func.get
        if (!within(l.start, l.end, lb, rb)) l update f2
        r foreach (r =>
          if (!within(r.start, r.end, lb, rb)) r update f2)
      }
      if (intersects(l.start, l.end, lb, rb)) l.updateRange(lb, rb)(f)
      r foreach (r =>
        if (intersects(r.start, r.end, lb, rb)) r.updateRange(lb, rb)(f))
      this.func = None
    }
  }

  def update(f: Int => T): Unit = {
    this.func = Some(f)
  }

  /** Checks whether (start to end) is within (lb to rb) */
  private def within(start: Int, end: Int, lb: Int, rb: Int) = {
    start >= lb && start <= rb && end >= lb && end <= rb
  }

  /** Checks whether (start to end) and (lb to rb) has points in common */
  private def intersects(start: Int, end: Int, lb: Int, rb: Int) = {
    (start >= lb && start <= rb) || (end >= lb && end <= rb) || (lb >= start && lb <= end) || (rb >= start && rb <= end)
  }

  override def equals(that: Any) = that match {
    case that: SegNode[T] => this.start == that.start && this.end == that.end && this.l == that.l && this.r == that.r && this.func == that.func
    case _                => false
  }
  override def hashCode = (start * 7) ^ (end * 13) ^ (l.hashCode * 17) ^ (r.map(_.hashCode).getOrElse(0) * 31)
  override def toString = {
    if (func.isDefined) ((start to end) map func.get) mkString " "
    else if (!r.isDefined) l.toString
    else l.toString + " " + r.get.toString
  }
}

object SegNode {
  def apply[T](l: MutableSegmentTree[T]) = {
    new SegNode(l, None, l.start, l.end, None)
  }

  def apply[T](l: MutableSegmentTree[T],
               r: MutableSegmentTree[T]) = {
    require(r.start == l.end + 1, "Right node range should start immediately after left")
    new SegNode(l, Some(r), l.start, r.end, None)
  }
}

class SegLeaf[T](val index: Int, var data: T) extends MutableSegmentTree[T] {
  override val size = 1

  def start = index
  def end = index
  def left = None
  def right = None

  def apply(i: Int): T = {
    require(i == index, "index is out of bounds")
    data
  }

  def updateRange(from: Int, to: Int)(f: Int => T): Unit = {
    if (index >= from && index <= to) update(f)
  }

  def update(f: Int => T): Unit = {
    data = f(index)
  }

  override def equals(that: Any) = that match {
    case that: SegLeaf[T] => this.index == that.index && this.data == that.data
    case _                => false
  }
  override def hashCode = (index * 17) ^ (data.hashCode * 31)
  override def toString = data.toString
}

/*
E. Копирование данных
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Очень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.

Более формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:

    Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.
    Определить значение в позиции x массива b, то есть найти значение bx.

Для каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.
Входные данные

В первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).

В следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.

Все числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.
Выходные данные

Для каждого запроса второго типа в отдельную строку выведите результат.
Примеры тестов
Входные данные

5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2

Выходные данные

0
3
-1
3
2
3
-1
*/
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

object CrocRound1Task5 extends App {

  type Range = ((Int, Int))
  def solve(a: Array[Long], b: Array[Long], actions: Seq[Action]): Seq[Long] = {
    val ranges = Stack.empty[Copy]
    val toPrint = ArrayBuffer.empty[Long]
    actions foreach {
      case c: Copy => ranges push c
      case Find(p) => toPrint += find(a, b, ranges, p)
    }
    toPrint
  }

  def find(a: Array[Long], b: Array[Long], ranges: Seq[Copy], pos: Int): Long = {
    val lastCopy = ranges find (c => pos >= c.posB && pos <= c.posB + c.length)
    if (lastCopy.isDefined) {
      val copy = lastCopy.get
      val shift = pos - copy.posB
      a(copy.posA + shift - 1)
    } else {
      b(pos - 1)
    }
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val a = readLine split ' ' map (_.toLong)
  val b = readLine split ' ' map (_.toLong)
  val actions: Seq[Action] = (0 until m) map { _ =>
    val s = readLine split ' ' map (_.toInt)
    if (s(0) == 1) Copy(s(1), s(2), s(3))
    else Find(s(1))
  }
  val res = solve(a, b, actions)
  res map (x => println(x))
}

abstract class Action {}

case class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}

case class Find(val pos: Int) extends Action {}

/*
E. Копирование данных
ограничение по времени на тест
2 секунды
ограничение по памяти на тест
256 мегабайт
ввод
standard input
вывод
standard output

Очень часто приходится копировать большие объемы данных. Такая операция может потребовать больших затрат компьютерных ресурсов. В связи с этим, в этой задаче вам предлагается придумать способ быстрого копирования некоторой части одного массива чисел в другой.

Более формально, вам задано два массива целых чисел a1, a2, ..., an и b1, b2, ..., bn длины n. Также есть m запросов двух типов:

    Скопировать подотрезок массива a длины k, начиная с позиции x, в массив b, начиная с позиции y, то есть выполнить by + q = ax + q для всех целых q (0 ≤ q < k). Операция задана корректно — оба подотрезка целиком содержатся в массивах a и b соответственно.
    Определить значение в позиции x массива b, то есть найти значение bx.

Для каждого запроса второго типа выведите результат — значение соответствующего элемента массива b.
Входные данные

В первой строке через пробел заданы два целых числа n и m (1 ≤ n, m ≤ 105) — количество элементов в массивах и количество запросов соответственно. Во второй строке задан массив целых чисел a1, a2, ..., an (|ai| ≤ 109). В третьей строке задан массив целых чисел b1, b2, ..., bn (|bi| ≤ 109).

В следующих m строках заданы описания запросов. В i-ой строке сначала задано целое число ti — тип i-го запроса (1 ≤ ti ≤ 2). Если ti = 1, то i-ый запрос обозначает операцию копирования, если ti = 2, то i-ый запрос обозначает взятие значения в массиве b. Если ti = 1, то после типа запроса записаны три целых числа xi, yi, ki (1 ≤ xi, yi, ki ≤ n) — параметры запроса копирования. Если ti = 2, то следом, после типа запроса, в строке записано целое число xi (1 ≤ xi ≤ n) — позиция в массиве b.

Все числа в строках разделены одиночными пробелами. Гарантируется, что все запросы корректны, то есть границы копирования не выходят за границы массивов a и b.
Выходные данные

Для каждого запроса второго типа в отдельную строку выведите результат.
Примеры тестов
Входные данные

5 10
1 2 0 -1 3
3 1 5 -2 0
2 5
1 3 3 3
2 5
2 4
2 1
1 2 1 4
2 1
2 4
1 4 2 1
2 2

Выходные данные

0
3
-1
3
2
3
-1
*/
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.Stack

object CrocRound1Task5 extends App {

  def solve(a: Array[Long], b: Array[Long], actions: Seq[Action]): Seq[Long] = {
    val tree = SegmentTree.fromSeq(b)
    val ranges = Stack.empty[Copy]
    val toPrint = ArrayBuffer.empty[Long]
    actions.foldLeft(tree)((tree, action) => action match {
      case Copy(pa, pb, len) => tree.updatedRange((pb - 1) until (pb + len - 1), i => a(i - pb + pa))
      case Find(p)           => { toPrint += tree(p - 1); tree }
    })
    toPrint
  }

  val (n, m) = {
    val l = readLine split ' ' map (_.toInt)
    (l(0), l(1))
  }
  val a = readLine split ' ' map (_.toLong)
  val b = readLine split ' ' map (_.toLong)
  val actions: Seq[Action] = (0 until m) map { _ =>
    val s = readLine split ' ' map (_.toInt)
    if (s(0) == 1) Copy(s(1), s(2), s(3))
    else Find(s(1))
  }
  val res = solve(a, b, actions)
  res foreach (x => println(x))
}

abstract class Action {}

case class Copy(val posA: Int, val posB: Int, val length: Int) extends Action {}

case class Find(val pos: Int) extends Action {}

// SegmentTree impl copy-paste
abstract class SegmentTree[T] {
  def size: Int
  def range: Range
  def apply(i: Int): T
  def updatedRange(r: Range, f: Int => T): SegmentTree[T]
  def updated(f: Int => T): SegmentTree[T]
}

object SegmentTree {

  def fromSeq[T](data: Seq[T]): SegmentTree[T] = {
    def unite(nodes: Seq[SegmentTree[T]]) = {
      if (nodes.length == 2) SegNode(nodes(0), nodes(1))
      else if (nodes.length == 1) SegNode(nodes(0))
      else throw new RuntimeException("Wrong collections to unite")
    }
    def formTreeRec(nodes: Seq[SegmentTree[T]]): SegmentTree[T] = {
      if (nodes.size == 1) nodes.head
      else {
        val united = (nodes grouped 2) map unite
        formTreeRec(united.toSeq)
      }
    }
    val iData = data.toIndexedSeq
    val leaves = (0 until iData.size) map (i => leaf(i, iData(i)))
    formTreeRec(leaves)
  }

  private def leaf[T](i: Int, d: T) = new SegLeaf(i, d)
}

case class SegNode[T](val left: SegmentTree[T],
                      val right: Option[SegmentTree[T]],
                      val range: Range,
                      val func: Option[Int => T]) extends SegmentTree[T] {
  require(range.step == 1, "non-standard ranges aren't supported")

  def size = range.size

  def hasRightBranch = right.isDefined

  def apply(i: Int): T = {
    require(range contains i, "index is out of bounds")
    if (func.isDefined) {
      (func.get)(i)
    } else if (left.range contains i) {
      left(i)
    } else {
      (right.get)(i)
    }
  }

  def updatedRange(r: Range, f: Int => T): SegmentTree[T] = {
    if (within(range, r)) {
      updated(f)
    } else if (intersects(range, r)) {
      new SegNode(left.updatedRange(r, f), right map (_.updatedRange(r, f)), range, None)
    } else {
      this
    }
  }

  def updated(f: Int => T): SegmentTree[T] = {
    new SegNode(left, right, range, Some(f))
  }

  override def toString = {
    if (!right.isDefined) left.toString
    else left.toString + " " + right.get.toString
  }

  /** Checks whether r1 is within r2 */
  private def within(r1: Range, r2: Range) = {
    r2.contains(r1.start) && r2.contains(r1.end)
  }

  /** Checks whether r1 and r2 has points in common */
  private def intersects(r1: Range, r2: Range) = {
    r2.contains(r1.start) || r2.contains(r1.end) || r1.contains(r2.start) || r1.contains(r2.end)
  }
}

object SegNode {
  def apply[T](l: SegmentTree[T]) = {
    new SegNode(l, None, l.range, None)
  }

  def apply[T](l: SegmentTree[T],
               r: SegmentTree[T]) = {
    val lr = l.range
    val rr = r.range
    require(rr.start == lr.end + 1, "Right node range should start immediately after left")
    new SegNode(l, Some(r), l.range.start to r.range.end, None)
  }
}

case class SegLeaf[T](val index: Int, val data: T) extends SegmentTree[T] {
  val size = 1
  lazy val range = index to index
  override def toString = data.toString

  def apply(i: Int): T = {
    require(i == index, "index is out of bounds")
    data
  }

  def updatedRange(r: Range, f: Int => T): SegmentTree[T] = {
    if (r contains index) updated(f)
    else this
  }

  def updated(f: Int => T): SegmentTree[T] =
    new SegLeaf[T](index, f(index))
}


object Solution extends App {

  def gcd(a: Int, b: Int): Int = {
    if (b == 0)
      a
    else
      gcd(b, a % b)
  }

  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).toList
  val d = data.tail.foldLeft(data.head) {
    case (prev, el) => gcd(prev, el)
  }
//  println(d)
  if ((data.max / d - data.length) % 2== 1)
    println("Alice")
  else
    println("Bob")
}

import scala.collection._

object A extends App {

  def gcd(x: Int, y: Int): Int =
    if (y == 0) x
    else gcd(y, x % y)

    def readString = Console.readLine
  def tokenizeLine = new java.util.StringTokenizer(readString)
  def readInts(n: Int) = { val t = tokenizeLine; Array.fill(n)(t.nextToken.toInt) }

  val n = readString.toInt
  val as = readInts(n)

  val g = as.reduce(gcd)
  val max = as.max
  val moves = max / g - n

  println(if (moves % 2 == 1) "Alice" else "Bob")
}

object C {
  def gcd(a: Int, b: Int): Int = {
    if (b == 0)
      a
    else
      gcd(b, a % b)
  }
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val t = (Nil : Seq[Int]).toBuffer
    for (i <- 1 to n)
      t += sc.nextInt
    val g = t.fold(t.head)(gcd(_, _))
    val cnt = t.sorted.last / g - t.size
    if (cnt % 2 == 1)
      println("Alice")
    else
      println("Bob")
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import scala.math._

object Main {

	def gcd(a : Int, b : Int) : Int = if (b==0) a else gcd(b,a%b)

	def main(args: Array[String]) {
		val n = in.rdInt
		var a = (for (i <- 1 to n) yield in.rdInt).sorted
		var z = a(0)
		for (i <- 1 until n) z = gcd(z,a(i))
		println( if ((a(n-1)/z-n)%2 == 1) "Alice" else "Bob" )
	}

	object in {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def FastReader = eat("")
		def eat(s : String) = st = new StringTokenizer(s)
		def rdInt = next.toInt
		def rdLong = next.toLong
		def rdDouble = next.toDouble
	}

}

object C347 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def gcd(x: Int, y: Int): Int = {
    if(x == 0) y else gcd(y % x, x)
  }

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    val finalgcd = input.foldLeft(input(0)){case (g, n) => gcd(g, n)}
    if((input.max/finalgcd - n) % 2 == 0) {
      println("Bob")
    } else {
      println("Alice")
    }
  }
}

object C347 {
  @inline def tokenizeLine = new java.util.StringTokenizer(scala.io.StdIn.readLine)

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n)
    if((input.max - n) % 2 == 0) {
      println("Bob")
    } else {
      println("Alice")
    }
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer
import scala.math._

object Main {

	def main(args: Array[String]) {
		val n = in.rdInt
		var a = (for (i <- 1 to n) yield in.rdInt).sorted
		var m = true
		for (i <- 1 until n)
			if (a(i)%a(0)!=0) m=false
		if (m) println( if (a(n-1)/a(0)%2 == 1) "Alice" else "Bob" )
		else println( if ( (a(n-1)-n)%2 == 1) "Alice" else "Bob" )
	}

	object in {
		val in = new BufferedReader(new InputStreamReader(System.in))
		var st = new StringTokenizer("")

		def next : String = {
			while (!st.hasMoreTokens) {
				val line = in.readLine
				if (line == null) return null
				eat(line)
			}
			st.nextToken
		}

		def FastReader = eat("")
		def eat(s : String) = st = new StringTokenizer(s)
		def rdInt = next.toInt
		def rdLong = next.toLong
		def rdDouble = next.toDouble
	}

}


import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val previousIndex = Array.ofDim[Int](100001)
  val distance = Array.ofDim[Int](100001)
  data.indices.foreach { i =>
    val value = data(i)
    val d = distance(value)
    if (d == 0) {
      if (previousIndex(value) != 0) {
        distance(value) = i + 1 - previousIndex(value)
      }
      previousIndex(value) = i + 1
    } else if (d > 0) {
      if (d == i + 1 - previousIndex(value))
        previousIndex(value) = i + 1
      else
        distance(value) = -1
    }
  }
  val res = (1 to 100000).collect{
    case (i) if previousIndex(i) != 0 && distance(i) != -1 => s"$i ${distance(i)}"
  }
  println(res.length)
  println(res.mkString("\n"))
}

import java.util.Scanner
import java.io.PrintWriter
import java.util.Arrays.binarySearch
import scala.annotation.tailrec
import scala.annotation.switch
import scala.collection.mutable
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ArrayBuffer
import scala.collection.immutable.TreeSet
import scala.util.Random
import scala.util.control.Breaks._

object P352B extends App {
  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)

  // N integers
  // a_1, ..., a_n
  // needs to find all values of x
  // x occurs in a_i
  // positions must form an arithmetic progression

  def solve(): Unit = {
    val N = sc.nextInt
    val idx = Array.fill(100001)(-1)
    val p, freq = Array.fill(100001)(0)

    @tailrec
    def loop(i: Int): Unit = {
      if (i == N) ()
      else {
        val x = sc.nextInt
        if (freq(x) < 0) ()
        else if (idx(x) < 0) {
          idx(x) = i
          freq(x) = 1
        }
        else if (p(x) == 0) {
          p(x) = i - idx(x)
          idx(x) = i
          freq(x) = 2
        }
        else if (idx(x) + p(x) == i) {
          idx(x) = i
          freq(x) += 1
        }
        else {
          freq(x) = -1
        }
        loop(i + 1)
      }
    }

    loop(0)
    out.println(freq.count(_ > 0))
    (1 to 100000).filter(freq(_) > 0).foreach { x =>
      out.println(x + " " + p(x))
    }
  }

  solve
  out.close
}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var count,differ: Int = 0
    var input: String = readLine
    var test = new Array[String](1000000)
    var rar = new Array[Int](1000000)
    var indexes  = new Array[Int](10000000)
    var fault = new Array[Int](1000000)
    var answers = new Array[String](10000000)
    var differs = new Array[Int](10000000)
    test = input.split(' ')
    for ( i <- 0 to n-1 ) {
      if ( rar(test(i).toInt) == 0 ) {
        rar(test(i).toInt) = 1
        indexes(test(i).toInt) = i;
      }
      else {
        rar(test(i).toInt) = rar(test(i).toInt) + 1
        if ( rar(test(i).toInt) == 2 ) {
          differ = i - indexes(test(i).toInt)
          differs(test(i).toInt) = differ
        }
        else
          differ = i - indexes(test(i).toInt)
          if ( differ != differs(test(i).toInt) )
            fault(test(i).toInt) = 1
          else
            indexes(test(i).toInt) = i
      }
    }
   for ( i <- 0 to 100000 )
     if (( rar(i) != 0 ) && ( fault(i) != 1 )) {
       answers(count) = i.toString +" "+ differs(i)
       count = count + 1
     }
   println(count);
   for ( i <- 0 to count-1 )
     println(answers(i))
  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexValue = data.indices.foldLeft(Map.empty[Int, List[Int]]) {
    case (acc, i) => acc + (data(i) -> (i :: acc.getOrElse(data(i), Nil)))
  }

  val res = indexValue.flatMap{
    case (value, list) if list.length == 1 => Some((value, 0))
    case (value, list) =>
      val distance = list.head - list(1)
      if (list.sliding(2).forall(i => i.head - i(1) == distance))
        Some(value, distance)
      else
        None
  }

  println(res.size)
  println(res.map{case (v, d) => s"$v $d"}.mkString("\n"))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt)
  val indexValue = data.indices.foldLeft(Map.empty[Int, (Int, Int)]) {
    case (acc, i) if !acc.contains(data(i)) =>
      acc + (data(i) -> (i, 0))
    case (acc, i) if acc(data(i))._2 == -1 => acc
    case (acc, i) if acc(data(i))._2 == 0 =>
      acc + (data(i) -> (i, i - acc(data(i))._1))
    case (acc, i) =>
      val distance = i - acc(data(i))._1
      acc + (data(i) -> (i, if (acc(data(i))._2 == distance) distance else - 1))
  }
  println(indexValue.filter(_._2._2 >= 0).keys.toList.sorted.map{case v => s"$v ${indexValue(v)._2}"}.mkString("\n"))

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var z,min,minpos,d: Int = 1000000
    var test = new Array[String](100000)
    var indexes = new Array[Int](100000)
    var input: String = readLine
    var answer: Boolean = false
    test = input.split(' ')
    for ( i <- 0 to n-1)
      indexes(i) = i
    for ( i <- 0 to n-1) {
      min = 100000
      minpos =indexes(i)
      for ( j <- i to n-1)
        if (test(indexes(j)).toInt < min) {
          min = test(indexes(j)).toInt
          minpos = j
        }
      z = indexes(minpos)
      indexes(minpos) = indexes(i)
      indexes(i) = z
    }
    z = 0
    while ( z != n) {
      min = z
      while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )
          z = z + 1
      minpos = z
      if ( (minpos - min) == 0)
        println(test(indexes(z))+" "+0.toString)
      else {
        answer = true
        d = indexes(min+1) - indexes(min)
        for ( j <- min to minpos-1)
          if ((indexes(j+1)-indexes(j)) != d)
            answer = false
        if (answer == true)
          println(test(indexes(z))+" "+d.toString)
      }
      z = z + 1
    }
  }

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var count,z,min,minpos,d: Int = 1000000
    var test = new Array[String](100000)
    var indexes = new Array[Int](100000)
    var input: String = readLine
    var answer: Boolean = false
    var answers = new Array[String](10000000)
    count = 0
    test = input.split(' ')
    for ( i <- 0 to n-1)
      indexes(i) = i
    for ( i <- 0 to n-1) {
      min = 100000
      minpos =indexes(i)
      for ( j <- i to n-1)
        if (test(indexes(j)).toInt < min) {
          min = test(indexes(j)).toInt
          minpos = j
        }
      z = indexes(minpos)
      indexes(minpos) = indexes(i)
      indexes(i) = z
    }
    z = 0
    while ( z != n) {
      min = z
      while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )
          z = z + 1
      minpos = z
      if ( (minpos - min) == 0) {
        answers(count) = test(indexes(z))+" "+0.toString
        count = count + 1
      }
      else {
        answer = true
        d = indexes(min+1) - indexes(min)
        for ( j <- min to minpos-1)
          if ((indexes(j+1)-indexes(j)) != d)
            answer = false
        if (answer == true) {
          answers(count) = test(indexes(z))+" "+d.toString
          count = count + 1
        }
      }
      z = z + 1
    }
    println(count)
    for ( i<-0 to count-1)
      println(answers(i))
  }

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var count,differ: Int = 0
    var input: String = readLine
    var test = new Array[String](1000000)
    var rar = new Array[Int](1000000)
    var indexes  = new Array[Int](10000000)
    var fault = new Array[Int](1000000)
    var answers = new Array[String](10000000)
    var differs = new Array[Int](10000000)
    test = input.split(' ')
    for ( i <- 0 to n-1 ) {
      if ( rar(test(i).toInt) == 0 ) {
        rar(test(i).toInt) = 1
        indexes(test(i).toInt) = i;
      }
      else {
        rar(test(i).toInt) = rar(test(i).toInt) + 1
        if ( rar(test(i).toInt) == 2 ) {
          differ = i - indexes(test(i).toInt)
          differs(test(i).toInt) = differ
        }
        else
          differ = i - indexes(test(i).toInt)
          if ( differ != differs(test(i).toInt) )
            fault(test(i).toInt) = 1
          else
            indexes(test(i).toInt) = i
      }
    }
   for ( i <- 0 to 99999 )
     if (( rar(i) != 0 ) && ( fault(i) != 1 )) {
       answers(count) = i.toString +" "+ differs(i)
       count = count + 1
     }
   println(count);
   for ( i <- 0 to count-1 )
     println(answers(i))
  }

}

object JeffandPeriods {
  def main(args: Array[String]): Unit = {
    var n: Int = readInt
    var z,min,minpos,d: Int = 1000000
    var test = new Array[String](100000)
    var indexes = new Array[Int](100000)
    var input: String = readLine
    var answer: Boolean = false
    test = input.split(' ')
    for ( i <- 0 to n-1)
      indexes(i) = i
    for ( i <- 0 to n-1) {
      min = 100000
      minpos =indexes(i)
      for ( j <- i to n-1)
        if (test(indexes(j)).toInt < min) {
          min = test(indexes(j)).toInt
          minpos = j
        }
      z = indexes(minpos)
      indexes(minpos) = indexes(i)
      indexes(i) = z
    }
    z = 0
    while ( z != n) {
      min = z
      while ( (z < n-1) && (test(indexes(z)) == test(indexes(z+1))) )
          z = z + 1
      minpos = z
      if ( (minpos - min) == 0)
        println(test(indexes(z)),0)
      else {
        answer = true
        d = indexes(min+1) - indexes(min)
        for ( j <- min to minpos-1)
          if ((indexes(j+1)-indexes(j)) != d)
            answer = false
        if (answer == true)
          println(test(indexes(z)),d)
      }
      z = z + 1
    }
  }

}


object Solution {
  def main(args: Array[String]) {
    val r = new Reader()
    val n, k = r.read[Int]
    val ls, as = r.read[Array[Long]](n)
    val zs = ls.zip(as)
    val ps = zs.map{ case (l, a) => l * a }.sum
    val pfs = pf(zs.map{ case (l, a) => l * (1 - a) })

    println(ps + (1 to n - k + 1).foldLeft(0.toLong) {
      case (acc, i) => math.max(acc, pfs(i + k - 1) - pfs(i - 1))
    })
  }

  def pf(as: Array[Long]) = as.scanLeft(0.toLong){ case (acc, a) => a + acc }
}

import java.io.{ BufferedReader, InputStreamReader }
import java.util.StringTokenizer

class Reader(br: BufferedReader) {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def this() = this(new InputStreamReader(System.in))

  def read[A](implicit read: Reader.Read[A]): A = read.apply(this)

  val tokenizer = new Tokenizer(br)
}

object Reader {
  class Read[A](val apply: Reader => A) {}

  object Read {
    implicit val string: Read[String] = new Read(_.tokenizer.next)
    implicit val int: Read[Int] = new Read(_.read[String].toInt)
    implicit val long: Read[Long] = new Read(_.read[String].toLong)
    implicit val double: Read[Double] = new Read(_.read[String].toDouble)

    implicit def tuple[A: Read, B: Read]: Read[(A, B)] = new Read(r => (r.read[A], r.read[B]))

    import scala.collection.generic.CanBuildFrom

    // what the f*ck??
    implicit def t[T[A], A: Read](n: Int)(implicit bf: CanBuildFrom[Nothing, A, T[A]]): Read[T[A]] =
      new Read(r => Iterator.continually(r.read[A]).take(n).to[T])
  }
}

class Tokenizer(br: BufferedReader) extends Iterator[String] {
  def this(isr: InputStreamReader) = this(new BufferedReader(isr))

  def hasNext = hasMoreTokens || {
    if (tokenizers.hasNext) {
      tokenizers.next()
      hasMoreTokens
    } else false
  }

  def next() = if (hasNext) { tokenizers.head.nextToken } else null

  private def hasMoreTokens = tokenizers.headOption.map(_.hasMoreTokens()).getOrElse(false)

  private val tokenizers =
    Iterator.continually(br.readLine()).takeWhile(_ != null).map(new StringTokenizer(_)).buffered
}

object A {
  def main(args: Array[String]) {
    val t = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    val n = t(0);
    val k = t(1);
    var as = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    var ts = scala.io.StdIn.readLine().split(" ").map( _.toInt );
    var s = 0;
    var dif = Array.ofDim[Int](n);
    var max_dif = 0;
    for(i <- 0 until n){
        if(ts(i) == 0) s += as(i);
        if(i - k >= 0 && ts(i - k) == 0)
            s -= as(i - k);
        if(i - k + 1 >= 0)
            dif(i - k + 1) = s;
            max_dif = math.max(max_dif, s);
    }
    var ans = 0;
    for(i <- 0 until n){
        if(ts(i) == 1)
            ans += as(i);
    }
    println(ans + max_dif);
  }
}