Andrewid the Android is a galaxy-famous detective. He is now chasing a criminal hiding on the planet Oxa-5, the planet almost fully covered with water.The only dry land there is an archipelago of n narrow islands located in a row. For more comfort let's represent them as non-intersecting segments on a straight line: island i has coordinates [li, ri], besides, ri < li + 1 for 1 ≤ i ≤ n - 1.To reach the goal, Andrewid needs to place a bridge between each pair of adjacent islands. A bridge of length a can be placed between the i-th and the (i + 1)-th islads, if there are such coordinates of x and y, that li ≤ x ≤ ri, li + 1 ≤ y ≤ ri + 1 and y - x = a. The detective was supplied with m bridges, each bridge can be used at most once. Help him determine whether the bridges he got are enough to connect each pair of adjacent islands.

The first line contains integers n (2 ≤ n ≤ 2·105) and m (1 ≤ m ≤ 2·105) — the number of islands and bridges. Next n lines each contain two integers li and ri (1 ≤ li ≤ ri ≤ 1018) — the coordinates of the island endpoints. The last line contains m integer numbers a1, a2, ..., am (1 ≤ ai ≤ 1018) — the lengths of the bridges that Andrewid got.

If it is impossible to place a bridge between each pair of adjacent islands in the required manner, print on a single line "No" (without the quotes), otherwise print in the first line "Yes" (without the quotes), and in the second line print n - 1 numbers b1, b2, ..., bn - 1, which mean that between islands i and i + 1 there must be used a bridge number bi.  If there are multiple correct answers, print any of them. Note that in this problem it is necessary to print "Yes" and "No" in correct case.

NoteIn the first sample test you can, for example, place the second bridge between points 3 and 8, place the third bridge between points 7 and 10 and place the first bridge between points 10 and 14.In the second sample test the first bridge is too short and the second bridge is too long, so the solution doesn't exist.

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        val x=this.length-that.length
        if(x==0L){
          this.idx-that.idx
        }else{
          x.signum
        }

      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-0 until n-1){
      val l=nextLong
      val r=nextLong
      gap(i)=new Gap(l-lastR,r-lastL,i)
      lastL=l
      lastR=r
    }
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      b+=new Bridge(nextLong,i+1)
    }

    import scala.util.Sorting.quickSort

    quickSort(gap)

    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val iter=b.iteratorFrom(new Bridge(gap(i).min,-1))
        if(iter.hasNext){
          val bg=iter.next
          if(bg.length>gap(i).max){
            dead=true;
            break

          }else{
            ans(gap(i).idx)=bg.idx
            b-=bg
          }
        }
        else{
          dead=true;
            break
        }
      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
     // out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
      if(n==100 && (m==200))
      out.println(gap(i))
    }
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100&& (m==200)){
//                out.println(gap(i)+" "+bg.length)
//                b.foreach(e=>out.println(e.length))
              }
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
      out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
      out.println(gap(i))
    }
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100&& (m==200)){
                out.println(gap(i)+" "+bg.length)
              }
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
     // out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
   //   out.println(gap(i))
    }
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100&& (m==200)){
                out.println(gap(i)+" "+bg.length)
              }
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
     // out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
   //   out.println(gap(i))
    }
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100&& (m==200)){
                out.println(gap(i)+" "+bg.length)
                b.foreach(e=>out.println(e.length))
              }
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        val x=this.max-that.max
        if(x>0){
          1
        }else if(x<0){
          -1
        }else{
          (this.min-that.min).signum
        }
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
//      out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
/*    for(i<-0 until gap.size){
      out.println(gap(i))
    }*/
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
     // out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    if(n==100&& (m==200)){
      out.println(gap.filter(_.max<=183).size+" "+b.filter(_.length<=183).size)
      out.println(gap.size+" "+b.size)
    }

    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
//      out.println(gap(i))
    }

    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
     // out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    if(n==100&& (m==200)){
      out.println(gap.filter(_.max<=183).size+" "+b.filter(_.length<=183).size)
    }

    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
//      out.println(gap(i))
    }

    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

      override def toString()={
        "("+this.min+","+this.max+","+this.idx+")"
      }
    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
     // out.println(gap(i-1)+" "+l+","+r+","+lastL+","+lastR)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    for(i<-0 until gap.size){
//      out.println(gap(i))
    }
    if(n==100&& (m==200)){
      out.println(gap.filter(_.max<=183).size+" "+b.filter(_.length<=183).size)
    }
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100&& (m==200)){
//                out.println(gap(i)+" "+bg.length)
//                b.foreach(e=>out.println(e.length))
              }
              break

            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }

          }
          case None => {dead=true;
            break
          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100){
                out.println(bg.length+" "+i)
              }

              break
            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }
          }
          case None => {dead=true;
            if(n==100){
                out.println(i)
              }
            break

          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              if(n==100&&(m==200)){
                out.println(bg.length+" "+i)
              }

              break
            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }
          }
          case None => {dead=true;
            if(n==100&&(m==200)){
                out.println(i)
              }
            break

          }
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}

object B2{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter,InputStream,BufferedReader,InputStreamReader}
  import java.util.{Locale, Scanner,StringTokenizer}
  import scala.collection.mutable.TreeSet
  class InputReader(val stream:InputStream ) {
    var st:StringTokenizer=new StringTokenizer("")
    val reader=new BufferedReader(new InputStreamReader(stream), 32768);

    def next():String = {
        while (!st.hasMoreTokens()){
          val currentLine = reader.readLine
          st=new StringTokenizer(currentLine)
        }
        return st.nextToken
    }

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

    def nextLong():Long = {
    	return next.toLong
    }
    def nextDouble:Double = {
      return next.toDouble
    }
  }

  def main(args: Array[String]){

    val in = new InputReader(System.in)
    val out = new PrintWriter(System.out)

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    //code starts here
    val n=nextInt
    val m=nextInt
    class Gap(imin:Long,imax:Long,iidx:Int)extends Ordered[Gap]{
      val min=imin
      val max=imax
      val idx=iidx
      def compare(that:Gap)={
        (this.max-that.max).signum
      }

    }
    class Bridge(ilength:Long,iidx:Int)extends Ordered[Bridge]{
      val length=ilength
      val idx=iidx
      def compare(that:Bridge)={
        (this.length-that.length).signum
      }
    }
    val gap=Array.ofDim[Gap](n-1)
    var lastL=nextLong
    var lastR=nextLong
    for(i<-1 until n){
      val l=nextLong
      val r=nextLong
      gap(i-1)=new Gap(l-lastR,r-lastL,i-1)
      lastL=l
      lastR=r
    }
    //val b=Array.ofDim[Bridge](m)
    val b=new TreeSet[Bridge]()
    for(i<-0 until m){
      //b(i)=new Bridge(nextLong,i+1)
      b+=new Bridge(nextLong,i+1)
    }
    import scala.util.Sorting.quickSort

    quickSort(gap)
    var dead=false
    val ans=Array.fill(n-1)(-1)

    breakable {
      for(i<-0 until n-1){
        val minl=gap(i).min
        b.find(_.length>=minl) match{
          case Some(bg)=> {
            if(bg.length>gap(i).max){
              dead=true;
              break
            }else{
              ans(gap(i).idx)=bg.idx
              b-=bg
            }
          }
          case None => {dead=true; break}
        }

      }
    }
    if(dead){
      out.println("No")
    }else{
      out.println("Yes")
      ans.foreach(e=>out.print(e+" "))
      out.println
    }
    //code ends here
    out.flush
    out.close
  }
}


You are given a matrix, consisting of $$$n$$$ rows and $$$m$$$ columns. The rows are numbered top to bottom, the columns are numbered left to right.Each cell of the matrix can be either free or locked.Let's call a path in the matrix a staircase if it:   starts and ends in the free cell;  visits only free cells;  has one of the two following structures:   the second cell is $$$1$$$ to the right from the first one, the third cell is $$$1$$$ to the bottom from the second one, the fourth cell is $$$1$$$ to the right from the third one, and so on;  the second cell is $$$1$$$ to the bottom from the first one, the third cell is $$$1$$$ to the right from the second one, the fourth cell is $$$1$$$ to the bottom from the third one, and so on.  In particular, a path, consisting of a single cell, is considered to be a staircase.Here are some examples of staircases:  Initially all the cells of the matrix are free.You have to process $$$q$$$ queries, each of them flips the state of a single cell. So, if a cell is currently free, it makes it locked, and if a cell is currently locked, it makes it free.Print the number of different staircases after each query. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.

The first line contains three integers $$$n$$$, $$$m$$$ and $$$q$$$ ($$$1 \le n, m \le 1000$$$; $$$1 \le q \le 10^4$$$) — the sizes of the matrix and the number of queries. Each of the next $$$q$$$ lines contains two integers $$$x$$$ and $$$y$$$ ($$$1 \le x \le n$$$; $$$1 \le y \le m$$$) — the description of each query.

Print $$$q$$$ integers — the $$$i$$$-th value should be equal to the number of different staircases after $$$i$$$ queries. Two staircases are considered different if there exists such a cell that appears in one path and doesn't appear in the other path.

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

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

    case class myType(var social: Int, var cp:  Int, var ind: Int)extends Ordered[myType] {
        override def compare(that: myType): Int = {
            if (social < that.social)
                return -1
            else if (social == that.social)
                return 0
            else
                return 1
        }
    }
    val rem = 1000000007

    val t = 1
    for (tt <- 1 to t) {
        val n = readInt()
        val m = readInt()
        val q = readInt()
        var cnt = 0L
        for (i <- 1 to n) {
            for (j <- 1 to m) {
                cnt += min(n - i, m - j) * 2L
                cnt += min(n - i, m - j + 1)
                cnt += min(n - i + 1, m - j)
                cnt += 1
            }
        }
        val arr = Array.ofDim[Boolean](n+1 ,m+1)
        var x = 0
        var y = 0
        var u1 = 0L
        var u2 = 0L
        var d1 = 0L
        var d2 = 0L
        var nx = 0
        var ny = 0
        for (k <- 1 to q) {
            x = readInt()
            y = readInt()
            u1 = 0L
            u2 = 0L
            d1 = 0L
            d2 = 0L
            nx = x
            ny = y-1
            while (nx >= 1 && ny >= 1 && !arr(nx)(ny)) {
                u1 += 1
                if (u1 % 2== 0)
                    ny -= 1
                else
                    nx -= 1
            }
            nx = x-1
            ny = y
            while (nx >= 1 && ny >= 1 && !arr(nx)(ny)) {
                u2 += 1
                if (u2 % 2== 1)
                    ny -= 1
                else
                    nx -= 1
            }
            nx = x+1
            ny = y
            while (nx <= n && ny <= m && !arr(nx)(ny)) {
                d1 += 1
                if (d1 % 2== 0)
                    nx += 1
                else
                    ny += 1
            }
            nx = x
            ny = y+1
            while (nx <= n && ny <= m && !arr(nx)(ny)) {
                d2 += 1
                if (d2 % 2== 1)
                    nx += 1
                else
                    ny += 1
            }
            //println(u1, u2, d1, d2)
            if (arr(x)(y))
                cnt += u1*d1 + u2*d2 + u1 + u2 + d1 + d2 + 1
            else
                cnt -= u1*d1 + u2*d2 + u1 + u2 + d1 + d2 + 1
            arr(x)(y) = !arr(x)(y)
            writer.println(cnt)
        }
    }
    writer.flush()
}


Consider the set of all nonnegative integers: $$${0, 1, 2, \dots}$$$. Given two integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^4$$$). We paint all the numbers in increasing number first we paint $$$0$$$, then we paint $$$1$$$, then $$$2$$$ and so on.Each number is painted white or black. We paint a number $$$i$$$ according to the following rules:    if $$$i = 0$$$, it is colored white;   if $$$i \ge a$$$ and $$$i - a$$$ is colored white, $$$i$$$ is also colored white;   if $$$i \ge b$$$ and $$$i - b$$$ is colored white, $$$i$$$ is also colored white;   if $$$i$$$ is still not colored white, it is colored black. In this way, each nonnegative integer gets one of two colors.For example, if $$$a=3$$$, $$$b=5$$$, then the colors of the numbers (in the order from $$$0$$$) are: white ($$$0$$$), black ($$$1$$$), black ($$$2$$$), white ($$$3$$$), black ($$$4$$$), white ($$$5$$$), white ($$$6$$$), black ($$$7$$$), white ($$$8$$$), white ($$$9$$$), ...Note that:    It is possible that there are infinitely many nonnegative integers colored black. For example, if $$$a = 10$$$ and $$$b = 10$$$, then only $$$0, 10, 20, 30$$$ and any other nonnegative integers that end in $$$0$$$ when written in base 10 are white. The other integers are colored black.   It is also possible that there are only finitely many nonnegative integers colored black. For example, when $$$a = 1$$$ and $$$b = 10$$$, then there is no nonnegative integer colored black at all. Your task is to determine whether or not the number of nonnegative integers colored black is infinite.If there are infinitely many nonnegative integers colored black, simply print a line containing "Infinite" (without the quotes). Otherwise, print "Finite" (without the quotes).

The first line of input contains a single integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases in the input. Then $$$t$$$ lines follow, each line contains two space-separated integers $$$a$$$ and $$$b$$$ ($$$1 \le a, b \le 10^4$$$).

For each test case, print one line containing either "Infinite" or "Finite" (without the quotes). Output is case-insensitive (i.e. "infinite", "inFiNite" or "finiTE" are all valid answers).

import java.util

import scala.collection.mutable
import scala.io.StdIn._

object Main extends App {

  def nod(a: Int, b: Int) = {
    var x = a
    var y = b
    while (x != 0 && y != 0) {
      if (x > y)
        x = x % y
      else
        y = y % x
    }
    x+y
  }

  val n = readLine().toInt

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    if (a % 2 == 0) {
      if ( nod(a,b) > 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    } else {
      //if (b % a == 0 && a != 1) {
      if ( nod(a,b) > 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    }

  }

/*

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    var st = "w"
    for (j <- 1 to (a max b)*12) {
      if ( (j >= a) && (j-a >= 0) && (st.charAt(j-a) == 'w') ) {
        st += 'w'
      } else if ( (j >= b) && (j-b >= 0) && (st.charAt(j-b) == 'w') ) {
        st += 'w'
      } else {
        st += 'b'
      }

    }

    print(a,b,st)
    if (st.charAt(st.length-1) == 'b' || st.charAt(st.length-2) == 'b')
      println("Infinite")
    else
      println("Finite")
  }
*/

}

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[this] val oj = System.getenv("ATCODER_DEBUG") == null
  @inline private final def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }
  @inline private final def debug(as: Array[Boolean]): Unit = if (!oj){ debug(as.map(x => if(x) "1" else "0").mkString) }
  @inline def debug(as: Array[Int]): Unit = if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debug(as: Array[Long]): Unit =if (!oj){ debug(as.mkString(" ")) }
  @inline private final def debugDim(m: Array[Array[Int]]): Unit = if (!oj){
    REP(m.length) { i =>
      debug(m(i))
    }
  }
  @inline private final 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()
    }
  }
  @inline def debug(s: => String): Unit = DEBUG {
    System.err.println(s)
  }
  @inline private final def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }
  private def isDebug[A](debug: => A, online: => A): A = {
    if (oj) online else debug
  }

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

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

    def nextInt(): Int = Integer.parseInt(next())
    def nextLong(): Long = java.lang.Long.parseLong(next())
    def nextChar(): Char = next().charAt(0)

    def ni(): Int = nextInt()
    def nl(): Long = nextLong()
    def nc(): Char = nextChar()
    def ns(): String = next()
    def ns(n: Int): Array[Char] = ns().toCharArray
    def na(n: Int, offset: Int = 0): Array[Int] = map(n)(_ => ni() + offset)
    def na2(n: Int, offset: Int = 0): (Array[Int], Array[Int]) = {
      val A1, A2 = Array.ofDim[Int](n)
      REP(n) { i =>
        A1(i) = ni() + offset
        A2(i) = ni() + offset
      }
      (A1, A2)
    }
    def nm(n: Int, m: Int): Array[Array[Int]] = {
      val A = Array.ofDim[Int](n, m)
      REP(n) { i =>
        REP(m) { j =>
          A(i)(j) = ni()
        }
      }
      A
    }
    def nal(n: Int): Array[Long] = map(n)(_ => nl())
    def nm_c(n: Int, m: Int): Array[Array[Char]] = map(n) (_ => ns(m))
  }

  def REP(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = offset
    val N = n + offset
    while(i < N) { f(i); i += 1 }
  }
  def REP_r(n: Int, offset: Int = 0)(f: Int => Unit): Unit = {
    var i = n - 1 + offset
    while(i >= offset) { f(i); i -= 1 }
  }
  def TO(from: Int, to: Int)(f: Int => Unit): Unit = {
    REP(to - from + 1, from)(f)
  }
  def map[@specialized A: ClassTag](n: Int, offset: Int = 0)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    REP(n)(i => res(i) = f(i + offset))
    res
  }

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

object Workspace {
  import Main._

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

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
  import Workspace._

  // toIntとか+7とかするならvalにしろ
  final private[this] val MOD = 1000000007

  def solve(): Unit = {
    REP(ni()) { _ =>
      val a, b = ni()
      if (gcd(a, b) == 1) {
        out.println("Finite")
      } else {
        out.println("Infinite")
      }
    }
  }
}

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

  override def apply(implicit io: IO): io.type = {
    repeat {
      val a, b = io.read[Long]
      io.writeLine(if (gcd(a, b) == 1L) "Finite" else "Infinite")
    }
  }

  @tailrec
  final def gcd(a: Long, b: Long): Long = if (b == 0) a else gcd(b, a%b)
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(implicit io: IO): io.type
  def repeat(f: => Unit)(implicit io: IO): io.type = {Utils.repeat(io.read[Int])(f); io}
  def main(args: Array[String]): Unit = apply(new IO(System.in, System.out)).close()
}
/****************************[Scala Collection Utils]****************************************/
object Utils {
  import scala.collection.mutable

  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]

  def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None

  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)

  implicit class GenericExtensions[A](a: A) {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }

  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](t: C[A]) {
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]

    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)

    def toMultiSet: Map[A, Int] = t.groupBy(identity).mapValues(_.size)
  }

  implicit class PairExtensions[A, B](p: (A, B)) {
    def key = p._1
    def value = p._2
    def toSeq(implicit ev: B =:= A): Seq[A] = Seq(p.key, ev(p.value))
  }

  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C]).withDefaultValue(b().result())
  }

  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](m: C[K, V]) {
    def toMutable: mutable.Map[K, V] = mutable.Map.empty[K, V] ++ m
  }

  implicit class SetExtensions[A, C[A] <: Set[A]](s: C[A]) {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }

  implicit class IterableExtensions[A, C[A] <: Seq[A]](s: C[A]) {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
  }

  implicit class BooleanExtensions(x: Boolean) {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "Yes" else "No"
  }

  implicit class IntExtensions(val x: Int) extends AnyVal {
    @inline def isEven = x%2 == 0
    @inline def isOdd = x%2 == 1
  }

  def desc[A](implicit order: Ordering[A]): Ordering[A] = order.reverse  //e.g. students.sortBy(_.height)(desc)

  def map[K] = new {
    def to[V](default: => V): mutable.Map[K, V] = using(_ => default)
    def using[V](f: K => V): mutable.Map[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }

  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]

  def memoize[A, B](f: A => B): A => B = map[A] using f
}
/***********************************[Scala I/O]*********************************************/
import java.io._, java.util.StringTokenizer
import scala.collection.generic.CanBuild

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

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

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

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

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

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

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

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

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

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

import java.util

import scala.collection.mutable
import scala.io.StdIn._

object Main extends App {

  def nod(a: Int, b: Int) = {
    var x = a
    var y = b
    while (x != 0 && y != 0) {
      if (x > y)
        x = x % y
      else
        y = y % x
    }
    x+y
  }

  val n = readLine().toInt

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    if (a % 2 == 0) {
      if ( nod(a,b) > 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    } else {
      if (b % a == 0 && a != 1) {
        println("Infinite")
      } else {
        println("Finite")
      }
    }

  }

/*

  for(i <- 0 to n-1) {
    val Array(a, b) = readLine().split(" ").map(_.toInt)

    var st = "w"
    for (j <- 1 to (a max b)*12) {
      if ( (j >= a) && (j-a >= 0) && (st.charAt(j-a) == 'w') ) {
        st += 'w'
      } else if ( (j >= b) && (j-b >= 0) && (st.charAt(j-b) == 'w') ) {
        st += 'w'
      } else {
        st += 'b'
      }

    }

    print(a,b,st)
    if (st.charAt(st.length-1) == 'b' || st.charAt(st.length-2) == 'b')
      println("Infinite")
    else
      println("Finite")
  }
*/

}


PizzaForces is Petya's favorite pizzeria. PizzaForces makes and sells pizzas of three sizes: small pizzas consist of $$$6$$$ slices, medium ones consist of $$$8$$$ slices, and large pizzas consist of $$$10$$$ slices each. Baking them takes $$$15$$$, $$$20$$$ and $$$25$$$ minutes, respectively.Petya's birthday is today, and $$$n$$$ of his friends will come, so he decided to make an order from his favorite pizzeria. Petya wants to order so much pizza that each of his friends gets at least one slice of pizza. The cooking time of the order is the total baking time of all the pizzas in the order.Your task is to determine the minimum number of minutes that is needed to make pizzas containing at least $$$n$$$ slices in total. For example:   if $$$12$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$12$$$ slices in total. He can order two small pizzas, containing exactly $$$12$$$ slices, and the time to bake them is $$$30$$$ minutes;  if $$$15$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$15$$$ slices in total. He can order a small pizza and a large pizza, containing $$$16$$$ slices, and the time to bake them is $$$40$$$ minutes;  if $$$300$$$ friends come to Petya's birthday, he has to order pizzas containing at least $$$300$$$ slices in total. He can order $$$15$$$ small pizzas, $$$10$$$ medium pizzas and $$$13$$$ large pizzas, in total they contain $$$15 \cdot 6 + 10 \cdot 8 + 13 \cdot 10 = 300$$$ slices, and the total time to bake them is $$$15 \cdot 15 + 10 \cdot 20 + 13 \cdot 25 = 750$$$ minutes;  if only one friend comes to Petya's birthday, he can order a small pizza, and the time to bake it is $$$15$$$ minutes.

The first line contains a single integer $$$t$$$ ($$$1 \le t \le 10^4$$$) — the number of testcases. Each testcase consists of a single line that contains a single integer $$$n$$$ ($$$1 \le n \le 10^{16}$$$) — the number of Petya's friends.

For each testcase, print one integer — the minimum number of minutes that is needed to bake pizzas containing at least $$$n$$$ slices in total.

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0 && rs > 0) {
                if (n <= 2)
                    rs = rs - 25 + 30
                else if (n <= 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 8)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            } else if (n > 8) rs = 25
            else if (n > 6) rs = 20
            else if (n > 0) rs = 15

            println(rs)
            t -= 1
        }

    }

    def main(args: Array[String]) {
        //multiTest(solve)
        solve()
    }
}

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

  val t = readInt()

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

    val ans = ((n max 6) + 1) / 2 * 5

    println(ans)
  }
}

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

  val f = readInt()

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

    val res = ((t max 6) + 1) / 2 * 5

    println(res)
  }
}

import scala.io.StdIn._

object Main {
  def main(args: Array[String]) = {
    def rep[A](n: Int)(f: => A) { if (n > 0) { f; rep(n - 1)(f) } }

    rep(readInt) {
      var in = BigDecimal(readLine)
      in = in.max(6)

      //so can get only 2,4,8,10,12
      //and for < 6 we want 6 slices either way
      in += (if (in % 2 != 0) 1 else 0)
      println((in * 2.5).toBigInt)
    }
  }
}

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

object Solution {
  def solve(input: Long): Long = {
    // a b c
    // 2*(a*3 + b*4 + c*5) >= input
    // 5*(a*3 + b*4 + c*5) = min
    // so you want to closest amount to input
    // actually we want to get exactly input or input * 2 most likely?

    //    val covered: Array[Boolean] = Array.fill(30000)(false)
    //    (0 to 1000).foreach { a =>
    //      (0 to 1000).foreach { b =>
    //        (0 to 1000).foreach { c =>
    //          covered(a*6+b*8+c*10) = true
    //        }
    //      }
    //    }
    //
    //    (0 to 3000).foreach { i =>
    //      if (!covered(i*2)) {
    //        println(s"not covered ${i*2}")
    //      }
    //    }
    //
    //    input

    // not covered 2
    // not covered 4
    val toCover = if (input < 6) 6 else if (input % 2 == 0) input else (input + 1)
    (toCover / 2) * 5
  }

  def run(test: Int, input: Scanner, output: PrintWriter): Unit = {
    output.println(solve(input.nextLong()))
  }

  def run(input: Scanner, output: PrintWriter): Unit = {
    val tests = input.nextInt()

    (1 to tests).foreach { test =>
      run(test, input, output)
      output.flush()
    }
  }

  def main(args: Array[String]): Unit = {
    run(new Scanner(System.in), new PrintWriter(System.out))
  }
}

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0) {
                if (n <= 2)
                    rs = rs - 25 + 30
                else if (n <= 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 8)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            }

            println(rs)
            t -= 1
        }

    }

    def main(args: Array[String]) {
        //multiTest(solve)
        solve()
    }
}

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0) {
                if (n == 2)
                    rs = rs - 25 + 30
                else if (n == 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 8)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            }

            println(rs)
            t -= 1
        }

    }

    def main(args: Array[String]) {
        //multiTest(solve)
        solve()
    }
}

import java.io.PrintWriter

import scala.collection.immutable.TreeSet
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import util.control.Breaks._

object Solution {
    val reader = scala.io.StdIn
    def readInt(): Int = reader.readLine().toInt
    def readLong(): Long = reader.readLine().toLong
    def readArrayInt(): Array[Int] = reader.readLine().split(" ").map(_.toInt)
    def readArrayLong(): Array[Long] = reader.readLine().split(" ").map(_.toLong)
    def readString(): String = reader.readLine()

    def multiTest(f: Int => Unit): Unit = {
        val t = readInt()
        for (i <- 1 to t) f(i)
    }

    def GCD(a: Int, b: Int): Int = {
        if (a == 0) return b
        GCD(b % a, a)
    }

    def solve(t: Int = 0): Unit = {
        var t = readInt()
        while (t > 0) {
            var n = readLong()
            var rs = n / 10 * 25
            n = n % 10

            if (n > 0) {
                if (n == 2)
                    rs = rs - 25 + 30
                else if (n == 4)
                    rs = rs - 25 + 35
                else if (n <= 6)
                    rs += 15
                else if (n <= 6)
                    rs += 20
                else if (n <= 10)
                    rs += 25
            }

            println(rs)
            t -= 1
        }

    }

    def main(args: Array[String]) {
        //multiTest(solve)
        solve()
    }
}

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

  val t = readInt()

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

    val ans = (n max 6) / 2 * 5

    println(ans)
  }
}

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

  val t = readInt()

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

    val ans = ((n + 9) / 10 * 25) min ((n + 7) / 8 * 20) min ((n + 5) / 6 * 15)

    println(ans)
  }
}


Gildong owns a bulgogi restaurant. The restaurant has a lot of customers, so many of them like to make a reservation before visiting it.Gildong tries so hard to satisfy the customers that he even memorized all customers' preferred temperature ranges! Looking through the reservation list, he wants to satisfy all customers by controlling the temperature of the restaurant.The restaurant has an air conditioner that has 3 states: off, heating, and cooling. When it's off, the restaurant's temperature remains the same. When it's heating, the temperature increases by 1 in one minute. Lastly, when it's cooling, the temperature decreases by 1 in one minute. Gildong can change the state as many times as he wants, at any integer minutes. The air conditioner is off initially.Each customer is characterized by three values: $$$t_i$$$ — the time (in minutes) when the $$$i$$$-th customer visits the restaurant, $$$l_i$$$ — the lower bound of their preferred temperature range, and $$$h_i$$$ — the upper bound of their preferred temperature range.A customer is satisfied if the temperature is within the preferred range at the instant they visit the restaurant. Formally, the $$$i$$$-th customer is satisfied if and only if the temperature is between $$$l_i$$$ and $$$h_i$$$ (inclusive) in the $$$t_i$$$-th minute.Given the initial temperature, the list of reserved customers' visit times and their preferred temperature ranges, you're going to help him find if it's possible to satisfy all customers.

Each test contains one or more test cases. The first line contains the number of test cases $$$q$$$ ($$$1 \le q \le 500$$$). Description of the test cases follows. The first line of each test case contains two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 100$$$, $$$-10^9 \le m \le 10^9$$$), where $$$n$$$ is the number of reserved customers and $$$m$$$ is the initial temperature of the restaurant. Next, $$$n$$$ lines follow. The $$$i$$$-th line of them contains three integers $$$t_i$$$, $$$l_i$$$, and $$$h_i$$$ ($$$1 \le t_i \le 10^9$$$, $$$-10^9 \le l_i \le h_i \le 10^9$$$), where $$$t_i$$$ is the time when the $$$i$$$-th customer visits, $$$l_i$$$ is the lower bound of their preferred temperature range, and $$$h_i$$$ is the upper bound of their preferred temperature range. The preferred temperature ranges are inclusive. The customers are given in non-decreasing order of their visit time, and the current time is $$$0$$$.

For each test case, print "YES" if it is possible to satisfy all customers. Otherwise, print "NO". You can print each letter in any case (upper or lower).

NoteIn the first case, Gildong can control the air conditioner to satisfy all customers in the following way:  At $$$0$$$-th minute, change the state to heating (the temperature is 0).  At $$$2$$$-nd minute, change the state to off (the temperature is 2).  At $$$5$$$-th minute, change the state to heating (the temperature is 2, the $$$1$$$-st customer is satisfied).  At $$$6$$$-th minute, change the state to off (the temperature is 3).  At $$$7$$$-th minute, change the state to cooling (the temperature is 3, the $$$2$$$-nd customer is satisfied).  At $$$10$$$-th minute, the temperature will be 0, which satisfies the last customer. In the third case, Gildong can change the state to heating at $$$0$$$-th minute and leave it be. Then all customers will be satisfied. Note that the $$$1$$$-st customer's visit time equals the $$$2$$$-nd customer's visit time.In the second and the fourth case, Gildong has to make at least one customer unsatisfied.

object Main {
  def main(args: Array[String]): Unit = {
    val q = readInt
    (0 until q).foreach((q) => f1)
  }

  def f1: Unit = {
    val Array(n, m) = readLine.split(" ").map(_.toLong)
    var l: Long = m
    var r: Long = m
    var i: Long = 0
    var t: Long = 0
    var b = true
    while (i < n) {
      val Array(ct, lt, ht) = readLine.split(" ").map(_.toLong)
      l -= (ct - t)
      r += (ct - t)
      t = ct
      l = Math.max(l, lt)
      r = Math.min(r, ht)
      if (l > r) b = false
      i = i + 1
    }
    if (b) println("YES") else println("NO")
  }
}


This problem is given in two versions that differ only by constraints. If you can solve this problem in large constraints, then you can just write a single solution to the both versions. If you find the problem too difficult in large constraints, you can write solution to the simplified version only.Waking up in the morning, Apollinaria decided to bake cookies. To bake one cookie, she needs n ingredients, and for each ingredient she knows the value ai — how many grams of this ingredient one needs to bake a cookie. To prepare one cookie Apollinaria needs to use all n ingredients.Apollinaria has bi gram of the i-th ingredient. Also she has k grams of a magic powder. Each gram of magic powder can be turned to exactly 1 gram of any of the n ingredients and can be used for baking cookies.Your task is to determine the maximum number of cookies, which Apollinaria is able to bake using the ingredients that she has and the magic powder.

The first line of the input contains two positive integers n and k (1 ≤ n, k ≤ 1000) — the number of ingredients and the number of grams of the magic powder. The second line contains the sequence a1, a2, ..., an (1 ≤ ai ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, needed to bake one cookie. The third line contains the sequence b1, b2, ..., bn (1 ≤ bi ≤ 1000), where the i-th number is equal to the number of grams of the i-th ingredient, which Apollinaria has.

Print the maximum number of cookies, which Apollinaria will be able to bake using the ingredients that she has and the magic powder.

NoteIn the first sample it is profitably for Apollinaria to make the existing 1 gram of her magic powder to ingredient with the index 2, then Apollinaria will be able to bake 4 cookies.In the second sample Apollinaria should turn 1 gram of magic powder to ingredient with the index 1 and 1 gram of magic powder to ingredient with the index 3. Then Apollinaria will be able to bake 3 cookies. The remaining 1 gram of the magic powder can be left, because it can't be used to increase the answer.

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)

  def getOneStepPrice(step: Int, ingStep:IngStep): Int = {
    if (step <= ingStep.lastStep)
      0 // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use remainder only if we are on this step
    } else {

      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {
    ingSteps.foldRight(0)((ingStep, t) => {
     t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var step = 1
    var cookies = 0
    var pRemainder = p
    var stop = false

    while(!stop) {
      val stepPrice = getStepPrice(step, ingSteps)

//      if (stepPrice > 0) {
//          println("Step " + step + " cookies " + cookies + " remainder " + pRemainder + " price " + stepPrice)
//      }

      if (stepPrice <= pRemainder) {
        cookies += 1
        step += 1
      } else {
        stop = true
      }
    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Long, required: Long, lastStep: Long, remainder: Long)

  def getOneStepPrice(step: Long, ingStep:IngStep): Long = {
    if (step <= ingStep.lastStep)
      0L // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use is there is a reminder on this step
    } else {
      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        (ingStep.required - ingStep.remainder) + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Long, ingSteps: IndexedSeq[IngStep]): Long = {
    ingSteps.foldRight(0L)((ingStep, t) => {
      t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices
      .map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i))))
      .sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var startStep = 0L //Math.max(1, ingSteps.head.lastStep)

    val fullPrice = getStepPrice(ingSteps.last.lastStep + 1, ingSteps) // Price to pay after everything is over

    var endStep = if (p >= fullPrice) ingSteps.last.lastStep + Math.round(p / fullPrice) else ingSteps.last.lastStep

    var stop = false
    var cookies = Math.max(startStep - 1, 0)

    while (!stop) {
//      println("Start " + startStep + " end " + endStep)
      val mid = startStep + Math.round((endStep - startStep) / 2)

      val stepPrice = getStepPrice(mid, ingSteps)
      cookies = mid

      if (stepPrice < p) {
        startStep = mid // Moving higher
      } else {
        endStep = mid // Moving lower
      }

      if (startStep == endStep) {
        stop = true
      } else if (startStep + 1 == endStep) {
        stop = true
        cookies = if (getStepPrice(endStep, ingSteps) <= p) endStep else startStep
      }
    }
//114, 117
//    var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait
//    var cookies = Math.max(step - 1, 0)
//    var pRemainder = p

//
//    while(!stop) {
//      val stepPrice = getStepPrice(step, ingSteps)
//
//      if (stepPrice <= pRemainder) {
//        cookies += 1
//        step += 1
//      } else {
//        stop = true
//      }
//    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)

  def getOneStepPrice(step: Int, ingStep:IngStep): Int = {
    if (step <= ingStep.lastStep)
      0 // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use remainder only if we are on this step
    } else {

      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {
    ingSteps.foldRight(0)((ingStep, t) => {
     t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var step = Math.max(1, ingSteps.head.lastStep - 1) // no need to wait
    var cookies = Math.max(step - 1, 0)
    var pRemainder = p
    var stop = false

    while(!stop) {
      val stepPrice = getStepPrice(step, ingSteps)

      if (stepPrice <= pRemainder) {
        cookies += 1
        step += 1
      } else {
        stop = true
      }
    }

    print(cookies)

  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  var Array(n, k) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt)
  var b = in.next().split(' ').map(_.toInt)
  var can = true
  var answer = 0
  while (can) {
    var minus = 0
    (0 until n).foreach { i =>
      val value = b(i) - a(i)
      if (value < 0) {
        minus -= value
        b(i) = 0
      } else {
        b(i) = value
      }
    }
    if (k >= minus) {
      k -= minus
      answer += 1
      can = true
    } else {
      can = false
    }
  }
  println(answer)

}

import Utils._, annotation.tailrec, collection.mutable, util._, control._, math.Ordering.Implicits._

object _670D1 extends CodeForcesApp {
  override def apply(io: IO) = {
    val n, k = io[Int]
    val perCookie, has = io[Vector, Long](n)

    val upperBound = 10 + ((has.sum + k)/perCookie.sum)

    def canBake(c: Long) = (c <= upperBound) && {  //can bake c cookies?
      val missing = perCookie.indices.foldLeft(0L) {
        case (needed, i) => needed + (((perCookie(i)*c) - has(i)) max 0)
      }
      missing <= k
    }

    io += (bitBinSearch(canBake) getOrElse 0L) max 0L
  }

  def bitBinSearch(f: Long => Boolean): Option[Long] = {
    var p = 0L
    var n = Long.MinValue
    var t = n >>> 1
    while (t > 0) {
      if (f(p|t)) p |= t
      if (f(n|t)) n |= t
      t >>= 1
    }
    Seq(p, n) find f
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = t.head.ensuring(t.size == 1)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap
    def prefixSum(implicit n: Numeric[A]) = t.scanLeft(n.zero) {case (acc, i) => n.plus(acc, i)}
    def suffixSum(implicit n: Numeric[A]) = t.scanRight(n.zero) {case (i, acc) => n.plus(acc, i)}
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_._1).mapValues(_._2)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_._1).mapValues(_.map(_._2).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    def bitCount: Int = java.lang.Long.bitCount(x)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(n.min(x, y), n.max(x, y), n.one)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: V): Dict[K, V] = Dict.empty[K, V] withDefaultValue default // also to(Dict.empty[K2, V])
  }
  def memoize[A, B](f: A => B): collection.Map[A, B] = new mutable.HashMap[A, B]() {
    override def apply(key: A) = getOrElseUpdate(key, f(key))
  }
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) Some(f) else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  val mod: Int = (1e9 + 7).toInt
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

  def till(delim: String): String = tokenizer().get.nextToken(delim)
  def tillEndOfLine(): String = till("\n\r")

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

  var separator = " "
  private[this] var isNewLine = true

  def +=[A](x: A)(implicit write: IO.Write[A]): this.type = {
    write(this)(x)
    this
  }
  def ++=[A: IO.Write](xs: Traversable[A]): this.type = (this += xs.size) appendNewLine xs

  def appendNewLine[A: IO.Write](x: A): this.type = {
    println()
    this += x
  }

  override def print(obj: String) = {
    if (isNewLine) isNewLine = false else super.print(separator)
    super.print(obj)
  }
  override def println() = if (!isNewLine) {
    super.println()
    isNewLine = true
  }
  override def close() = {
    flush()
    in.close()
    super.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r[C, A](r[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val boolean                                      : Read[Boolean]      = string.map(_.toBoolean)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r[A], r[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r[A], r[B], r[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r[A], r[B], r[C], r[D]))
  }
  trait Write[-A] {
    def apply(out: PrintWriter)(x: A): Unit
  }
  trait DefaultWrite {
    implicit def any[A]: Write[A] = Write(_.toString)
  }
  object Write extends DefaultWrite {
    def apply[A](f: A => String) = new Write[A] {
      override def apply(out: PrintWriter)(x: A) = out.print(f(x))
    }
    implicit val boolean: Write[Boolean] = Write(b => if (b) "YES" else "NO")
    implicit def tuple2[A, B]: Write[(A, B)] = Write {case (a, b) => s"$a $b"}
    implicit def iterable[A](implicit write: Write[A]): Write[Traversable[A]] = new Write[Traversable[A]] {
      override def apply(out: PrintWriter)(xs: Traversable[A]) = {
        xs foreach write(out)
        out.println()
      }
    }
  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)

    val a = readInts()
    val b = readInts()

    val minSteps = a.indices.map(i => (i, Math.floorDiv(b(i), a(i)))).sortBy(_._2) // we now have i, steps sorted from lowest

    var pRemainder = numberPowder(1)
    var cookies = if (minSteps.isEmpty) 0 else minSteps.head._2 // Initialise from minimum steps

    // println("Minimum: " + cookies)

    minSteps.indices.foreach(i => {
      val minStep = minSteps(i)
      val aI = a(minStep._1)
      val bI = b(minStep._1)
      val addOn = Math.floorMod(bI, aI)

//      println("i: " + minStep._1 +  " value " + aI + " steps " + minStep._2 + " addon " + addOn)

      val nextStep = if (i < minSteps.size - 1) minSteps(i + 1)._2 else -1

      if (pRemainder > 0) {
        val extraPowder = aI - addOn
        val extraStep = if ((pRemainder - extraPowder) > 0 && extraPowder > 0) {
          pRemainder -= extraPowder

          if (nextStep > minStep._2) {
            cookies += 1 // enough for 1 more at least
          }
          1
        } else {
          0
        }

        if (i < minSteps.size - 1 && nextStep > 0) {
          val eatHere = nextStep - (minStep._2 + extraStep) // this is how much more room we have to use powder
          // for this ingredient

          if (eatHere > 0) {
            val moreTooCook = Math.floorDiv(pRemainder, aI)
            pRemainder -= moreTooCook // eat as much as we can
            cookies += moreTooCook
          }
        }
      }
    })

    if (pRemainder >= a.sum) {
      cookies += Math.floorMod(pRemainder, a.sum) // finish the remainder
    }

    print(cookies)

  }
}

import scala.io.StdIn.readLine

object MagicPowder {

  def readInts(): Array[Int] = {
    readLine().split("\\s+").map(s => s.toInt)
  }

  case class IngStep(index: Int, required: Int, lastStep: Int, remainder: Int)

  def getOneStepPrice(step: Int, ingStep:IngStep): Int = {
    if (step <= ingStep.lastStep)
      0 // No need to use anything
    else
      if (step == ingStep.lastStep + 1 && ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder // use remainder only if we are on this step
    } else {

      // If there is a remainder, we need 1 step less
      if (ingStep.remainder > 0) {
        ingStep.required - ingStep.remainder + (step - ingStep.lastStep - 1) * ingStep.required
      } else {
        // all the steps are the same
        (step - ingStep.lastStep) * ingStep.required
      }
    }
  }

  def getStepPrice(step: Int, ingSteps: IndexedSeq[IngStep]): Int = {
    ingSteps.foldRight(0)((ingStep, t) => {
     t + getOneStepPrice(step, ingStep)
    })
  }

  def main(args: Array[String]): Unit = {
    val numberPowder = readInts()

    val n = numberPowder(0)
    val p = numberPowder(1)

    val a = readInts()
    val b = readInts()

    val ingSteps = a.indices.map(i => IngStep(i, a(i), Math.floorDiv(b(i), a(i)), Math.floorMod(b(i), a(i)))).sortBy(m => m.lastStep) // we now have i, steps sorted from lowest

    var step = ingSteps.head.lastStep - 1 // no need to wait
    var cookies = Math.max(step - 1, 0)
    var pRemainder = p
    var stop = false

    while(!stop) {
      val stepPrice = getStepPrice(step, ingSteps)

      if (stepPrice <= pRemainder) {
        cookies += 1
        step += 1
      } else {
        stop = true
      }
    }

    print(cookies)

  }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  var Array(n, k) = in.next().split(' ').map(_.toInt)
  val a = in.next().split(' ').map(_.toInt)
  var b = in.next().split(' ').map(_.toInt)
  var can = true
  var answer = 0
  while (can) {
    b = b.zip(a).map(i => i._1 - i._2)
    if (k > - b.filter(_ < 0).sum) {
      k -= b.filter(_ < 0).sum
      answer += 1
      b = b.map(i => Math.max(0, i))
      can = true
    } else {
      can = false
    }
  }
  println(answer)

}