Vladimir would like to prepare a present for his wife: they have an anniversary! He decided to buy her exactly $$$n$$$ flowers.Vladimir went to a flower shop, and he was amazed to see that there are $$$m$$$ types of flowers being sold there, and there is unlimited supply of flowers of each type. Vladimir wants to choose flowers to maximize the happiness of his wife. He knows that after receiving the first flower of the $$$i$$$-th type happiness of his wife increases by $$$a_i$$$ and after receiving each consecutive flower of this type her happiness increases by $$$b_i$$$. That is, if among the chosen flowers there are $$$x_i > 0$$$ flowers of type $$$i$$$, his wife gets $$$a_i + (x_i - 1) \cdot b_i$$$ additional happiness (and if there are no flowers of type $$$i$$$, she gets nothing for this particular type).Please help Vladimir to choose exactly $$$n$$$ flowers to maximize the total happiness of his wife.

The first line contains the only integer $$$t$$$ ($$$1 \leq t \leq 10\,000$$$), the number of test cases. It is followed by $$$t$$$ descriptions of the test cases. Each test case description starts with two integers $$$n$$$ and $$$m$$$ ($$$1 \le n \le 10^9$$$, $$$1 \le m \le 100\,000$$$), the number of flowers Vladimir needs to choose and the number of types of available flowers. The following $$$m$$$ lines describe the types of flowers: each line contains integers $$$a_i$$$ and $$$b_i$$$ ($$$0 \le a_i, b_i \le 10^9$$$) for $$$i$$$-th available type of flowers. The test cases are separated by a blank line. It is guaranteed that the sum of values $$$m$$$ among all test cases does not exceed $$$100\,000$$$.

For each test case output a single integer: the maximum total happiness of Vladimir's wife after choosing exactly $$$n$$$ flowers optimally.

NoteIn the first example case Vladimir can pick 1 flower of the first type and 3 flowers of the second type, in this case the total happiness equals $$$5 + (1 + 2 \cdot 4) = 14$$$.In the second example Vladimir can pick 2 flowers of the first type, 2 flowers of the second type, and 1 flower of the third type, in this case the total happiness equals $$$(5 + 1 \cdot 2) + (4 + 1 \cdot 2) + 3 = 16$$$.

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, ab.b))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a <= ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1) min n
        val onPosA = if (pos > 0) abs(pos - 1).a else Int.MaxValue
        val x = if (ab.a < onPosA) prefixSums(pos min (n - 1)) + ab.a + ab.b * (n - pos - 1)
        else prefixSums(pos) + ab.b * (n - pos)

        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, ab.b))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a < ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1)
        val onPos = if (pos >  0) abs(pos-1) else ab
        val x = if (pos < i) if (ab.a <= onPos.a) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0
        else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0

        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

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

    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val as, bs = Array.ofDim[Long](m)
      for (i <- 0 until m) {
        as(i) = nextInt
        bs(i) = nextInt
      }

      val bestB = (0 until m).maxBy {
        i => bs(i) * Int.MaxValue + as(i)
      }

      val maxB = bs(bestB)
      val betterAs = as.zipWithIndex.collect {
        case (a, i) if a > maxB && i != bestB =>
          a
      }.take(n)
      val takeBs = Math.max(0, n - betterAs.length)
      val res = if (takeBs == 0) betterAs.sum
      else if (takeBs == 1) {
        as.zipWithIndex.collect {
          case (a, i) if a > maxB =>
            a
        }.take(n).sum
      } else betterAs.sum + as(bestB) + maxB * (takeBs - 1)
//println(bestB, betterAs.mkString(" "), takeBs)

      out.println(res)
    }
    out.flush()
  }

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

object C {
  import InOut._
  def main(args: Array[String]): Unit = {
case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, -ab.b))

      val maxAB = abs.maxBy(ab => (ab.b, ab.a))

      var res1 = abs.take(n).map(_.a).sum
      var aSum = 0L
      var maxB = 0L
      var count = 0
      var passedAB = false

      for (ab <- abs) {
        if (ab.a > maxAB.b) {
          count += 1
          aSum += ab.a
          if (ab.b > maxB) {
            maxB = ab.b
          }
        }
        if (ab == maxAB) passedAB = true
        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        val z = if (!passedAB && ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L
//        println(count, aSum, x, y, z)
        val xy = x max y max z
        if (xy > res1) res1 = xy
      }

      out.println(res1)
    }
    out.flush()
  }

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

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

    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val as, bs = Array.ofDim[Long](m)
      for (i <- 0 until m) {
        as(i) = nextInt
        bs(i) = nextInt
      }

      val bestB = (0 until m).maxBy {
        i => bs(i) * Int.MaxValue + as(i)
      }

      val maxB = bs(bestB)
      val betterAs = as.zipWithIndex.collect {
        case (a, i) if a > maxB && i != bestB =>
          a
      }.take(n)
      val takeBs = Math.max(0, n - betterAs.length)
      val res = if (takeBs == 0) betterAs.sum
      else if (takeBs == 1) {
        val res = as.zipWithIndex.collect {
          case (a, i) if a > maxB =>
            a
        }.take(n).sum
      } else betterAs.sum + as(bestB) + maxB * (takeBs - 1)
//println(bestB, betterAs.mkString(" "), takeBs)

      out.println(res)
    }
    out.flush()
  }

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

object C {
  import InOut._
  def main(args: Array[String]): Unit = {
case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, -ab.b))

      val maxAB = abs.maxBy(ab => (ab.b, ab.a))

      var res1 = 0L
      var aSum = 0L
      var maxB = 0L
      var count = 0
      var passedAB = false

      for (ab <- abs) {
        count += 1
        aSum += ab.a
        if (ab.b > maxB) {
          maxB = ab.b
        }
        if (ab == maxAB) passedAB = true
        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        //println(count, aSum, x, y)
        val xy = x max y
        if (xy > res1) res1 = xy
      }

      out.println(res1)
    }
    out.flush()
  }

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

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, ab.b))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a <= ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1)
//        println(pos, ab, i)
        val x = if (pos < i) if (pos < n) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0
        else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0

        //        if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {
        //          count += 1
        //          aSum += ab.a
        //          if (ab.b > maxB) {
        //            maxB = ab.b
        //          }
        //        }
        //        if (ab == maxAB) passedAB = true
        //        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        //        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        //        val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L
        ////        println(count, aSum, x, y, z)
        //        val xy = x max y max z
        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

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

    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val as, bs = Array.ofDim[Long](m)
      for (i <- 0 until m) {
        as(i) = nextInt
        bs(i) = nextInt
      }

      val bestB = (0 until m).maxBy {
        i => bs(i) * Int.MaxValue + as(i)
      }

      val maxB = bs(bestB)
      val betterAs = as.zipWithIndex.collect {
        case (a, i) if a > maxB && i != bestB =>
          a
      }.take(n)
      val takeBs = Math.max(0, n - betterAs.length)

      val res1 = if (takeBs == 0) betterAs.sum
      else if (takeBs == 1) {
        as.zipWithIndex.collect {
          case (a, i) if a > maxB =>
            a
        }.take(n).sum
      } else (betterAs.sum + as(bestB) + maxB * (takeBs - 1))
//println(bestB, betterAs.mkString(" "), takeBs)

      val res2 = as.sorted.reverse.take(n).sum
      val res = res1 max res2

      out.println(res)
    }
    out.flush()
  }

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

object C {
  import InOut._
  def main(args: Array[String]): Unit = {
case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, -ab.b))

      val maxAB = abs.maxBy(ab => (ab.b, ab.a))

      var res1 = abs.take(n).map(_.a).sum
      var aSum = 0L
      var maxB = 0L
      var count = 0
      var passedAB = false

      for (ab <- abs) {
        if (ab.a > maxAB.b) {
          count += 1
          aSum += ab.a
          if (ab.b > maxB) {
            maxB = ab.b
          }
        }
        if (ab == maxAB) passedAB = true
        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L
//        println(count, aSum, x, y, z)
        val xy = x max y max z
        if (xy > res1) res1 = xy
      }

      out.println(res1)
    }
    out.flush()
  }

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

object C {
  import InOut._
  def main(args: Array[String]): Unit = {
case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, -ab.b))

      val maxAB = abs.maxBy(ab => (ab.b, ab.a))

      var res1 = abs.take(n).map(_.a).sum
      var aSum = 0L
      var maxB = 0L
      var count = 0
      var passedAB = false

      for (ab <- abs) {
        if (ab.a > maxAB.b) {
          count += 1
          aSum += ab.a
          if (ab.b > maxB) {
            maxB = ab.b
          }
        }
        if (ab == maxAB) passedAB = true
        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        //println(count, aSum, x, y)
        val xy = x max y
        if (xy > res1) res1 = xy
      }

      out.println(res1)
    }
    out.flush()
  }

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

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, ab.b))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a <= ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1)
//        println(pos, ab, i)
        val onPos = if (pos > 0) abs(pos-1) else ab
        val x = if (pos < i) if (ab.a <= onPos.a) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0
        else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0

        //        if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {
        //          count += 1
        //          aSum += ab.a
        //          if (ab.b > maxB) {
        //            maxB = ab.b
        //          }
        //        }
        //        if (ab == maxAB) passedAB = true
        //        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        //        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        //        val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L
        ////        println(count, aSum, x, y, z)
        //        val xy = x max y max z
        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, ab.b))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a < ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1)
        val x = if (pos < i) if (pos < n) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0
        else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0

        //        if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {
        //          count += 1
        //          aSum += ab.a
        //          if (ab.b > maxB) {
        //            maxB = ab.b
        //          }
        //        }
        //        if (ab == maxAB) passedAB = true
        //        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        //        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        //        val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L
        ////        println(count, aSum, x, y, z)
        //        val xy = x max y max z
        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, -ab.b))

      val maxAB = abs.maxBy(ab => (ab.b, ab.a))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a < ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1)
        val x = if (pos < i) if (pos < n) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0
        else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0

        //        if (aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) > aSum + maxAB.a + (n - count - 1) * maxAB.b) {
        //          count += 1
        //          aSum += ab.a
        //          if (ab.b > maxB) {
        //            maxB = ab.b
        //          }
        //        }
        //        if (ab == maxAB) passedAB = true
        //        val x = if (count <= n) aSum + maxB * (n - count) else 0L
        //        val y = if (!passedAB && count < n) aSum + maxAB.a + maxAB.b * (n - count - 1) else 0L
        //        val z = if (ab.a <= maxAB.b) aSum + ab.a + (n - count - 1) * math.max(maxB, ab.b) else 0L
        ////        println(count, aSum, x, y, z)
        //        val xy = x max y max z
        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}

object C {

  import InOut._

  def main(args: Array[String]): Unit = {
    case class AB(a: Long, b: Long)
    for (_ <- 1 to nextInt) {
      val n, m = nextInt
      val abs = Array.fill(m) {
        AB(nextInt, nextInt)
      }.sortBy(ab => (-ab.a, ab.b))

      var res1 = abs.take(n).map(_.a).sum
      val prefixSums = abs.map(_.a).scan(0L)(_ + _)

      for (i <- abs.indices) {
        val ab = abs(i)

        @annotation.tailrec
        def binSearch(low: Int, hi: Int): Int = {
          if (hi < low) low
          else {
            val mid = (low + hi) / 2
            if (abs(mid).a < ab.b) binSearch(low, mid - 1)
            else binSearch(mid + 1, hi)
          }
        }

        val pos = binSearch(0, m - 1)
        val onPos = if (pos > 0) abs(pos - 1) else ab
        val x = if (pos < i) if (ab.a < onPos.a) prefixSums(pos) + ab.a + ab.b * (n - pos - 1) else 0
        else if (pos <= n) prefixSums(pos) + ab.b * (n - pos) else 0

        if (x > res1) res1 = x
      }

      out.println(res1)
    }
    out.flush()
  }

  final object InOut {
    val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)
    private[this] var tokenizer: java.util.StringTokenizer = _

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

    def nextInt = Integer.parseInt(nextToken)

    def nextLong = java.lang.Long.parseLong(nextToken)

    def nextBig = BigInt(nextToken)

    def nextInts(n: Int) = Array.fill(n) {
      nextInt
    }

    def nextLongs(n: Int) = Array.fill(n) {
      nextLong
    }

    def nextBigs(n: Int) = Array.fill(n) {
      nextBig
    }

    def nextLine = in.readLine
  }

}


You are given an array $$$a$$$ consisting of $$$n$$$ integers.In one move, you can choose some index $$$i$$$ ($$$1 \le i \le n - 2$$$) and shift the segment $$$[a_i, a_{i + 1}, a_{i + 2}]$$$ cyclically to the right (i.e. replace the segment $$$[a_i, a_{i + 1}, a_{i + 2}]$$$ with $$$[a_{i + 2}, a_i, a_{i + 1}]$$$). Your task is to sort the initial array by no more than $$$n^2$$$ such operations or say that it is impossible to do that.You have to answer $$$t$$$ independent test cases.

The first line of the input contains one integer $$$t$$$ ($$$1 \le t \le 100$$$) — the number of test cases. Then $$$t$$$ test cases follow. The first line of the test case contains one integer $$$n$$$ ($$$3 \le n \le 500$$$) — the length of $$$a$$$. The second line of the test case contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$1 \le a_i \le 500$$$), where $$$a_i$$$ is the $$$i$$$-th element $$$a$$$. It is guaranteed that the sum of $$$n$$$ does not exceed $$$500$$$.

For each test case, print the answer: -1 on the only line if it is impossible to sort the given array using operations described in the problem statement, or the number of operations $$$ans$$$ on the first line and $$$ans$$$ integers $$$idx_1, idx_2, \dots, idx_{ans}$$$ ($$$1 \le idx_i \le n - 2$$$), where $$$idx_i$$$ is the index of left border of the segment for the $$$i$$$-th operation. You should print indices in order of performing operations.

//package codeforces.contests._1374

object CyclicShiftsSorting {

  def countInversions(arr: Array[Int]): Int = {
    arr.indices.foldLeft(0)((accI, i) =>
      accI + (i + 1 until arr.length).foldLeft(0)((accJ, j) =>
        accJ + (if (arr(i) > arr(j)) 1 else 0)))
  }

  def main(args: Array[String]): Unit = {
    println({
      for (_ <- 1 to io.StdIn.readInt()) yield {
        val n = io.StdIn.readInt()
        val seq = io.StdIn.readLine().split(" ").map(_.toInt)

        val originalZipped = seq.zipWithIndex
        val sortedSeq = originalZipped.sortBy(_._1).toList

        def rotateRight(i: Int): Unit = {
          val a = originalZipped(i)
          val b = originalZipped(i + 1)
          val c = originalZipped(i + 2)

          originalZipped(i) = c
          originalZipped(i + 1) = a
          originalZipped(i + 2) = b
        }

        @scala.annotation.tailrec
        def loop(pos: Int, turn: List[(Int, Int)], stillOdd: Boolean, result: List[Int]): List[Int] = {
          turn match {
            case Nil if !stillOdd => result
            case Nil if stillOdd => Nil
            case f :: s :: tail if stillOdd && f._1 == s._1 =>
              val idS = originalZipped.indexOf(s)
              val tempR = (idS - 2 to pos by -2).foldLeft(result) { (acc, i) => rotateRight(i); (i + 1) :: acc }

              val newR = if (pos + 1 < n && originalZipped(pos + 1) == s) {
                rotateRight(pos)
                rotateRight(pos)
                pos + 1 :: pos + 1 :: tempR
              } else tempR
              loop(pos + 1, f :: tail, stillOdd = false, newR)

            case h :: tail =>
              val idV = originalZipped.indexOf(h)
              val tempR = (idV - 2 to pos by -2).foldLeft(result) { (acc, i) => rotateRight(i); (i + 1) :: acc }

              val newR = if (pos + 1 < n && originalZipped(pos + 1) == h) {
                rotateRight(pos)
                rotateRight(pos)
                pos + 1 :: pos + 1 :: tempR
              } else tempR
              loop(pos + 1, tail, stillOdd, newR)
          }
        }

        val areInversionsOdd = countInversions(seq) % 2 == 1
        val allDistinct = seq.distinct.length == n

        if (areInversionsOdd && allDistinct) "-1" else {
          val result = loop(0, sortedSeq, areInversionsOdd, Nil)
          s"${result.length}\n${result.reverse.mkString(" ")}"
        }
      }
    }.mkString("\n"))
  }
}


Iahub and Iahubina went to a date at a luxury restaurant. Everything went fine until paying for the food. Instead of money, the waiter wants Iahub to write a Hungry sequence consisting of n integers. A sequence a1, a2, ..., an, consisting of n integers, is Hungry if and only if:   Its elements are in increasing order. That is an inequality ai < aj holds for any two indices i, j (i < j).  For any two indices i and j (i < j), aj must not be divisible by ai. Iahub is in trouble, so he asks you for help. Find a Hungry sequence with n elements.

The input contains a single integer: n (1 ≤ n ≤ 105).

Output a line that contains n space-separated integers a1 a2, ..., an (1 ≤ ai ≤ 107), representing a possible Hungry sequence. Note, that each ai must not be greater than 10000000 (107) and less than 1. If there are multiple solutions you can output any one.

import java.util.StringTokenizer

object _327B extends App {
  var token = new StringTokenizer("")
  def next = {
    while (!token.hasMoreTokens()) token = new StringTokenizer(readLine)
    token.nextToken()
  }
  val n = next.toInt
  var a = Vector[Int]()
  val isok = Array.fill(10000001)(true)
  var i = 2

  while(a.size < n) {
    if (isok(i)) {
      a = a :+ i
      var j = i + i
      while(j < isok.length) {
        isok(j) = false
        j += i
      }
    }
    i += 1
  }

  println(a.mkString(" "))
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val array = Array.ofDim[Boolean](2000002)
  array(0) = true
  array(1) = true
  (2 to 2000001).foreach { i =>
    if (!array(i)) {
      var j = 2 * i
      while (j <= 2000001) {
        array(j) = true
        j += i
      }
    }
  }
  println(array.indices.filter(i => !array(i)).take(n).mkString(" "))
}

object B extends App {

  def readString = Console.readLine
  def readInts = readString.split(" ").map(_.toInt)

  val n = readString.toInt

  val LIMIT = 1300000
  val prime = Array.fill(LIMIT)(true)
  prime(0) = false

  Stream.from(2).takeWhile(i => i*i < LIMIT).filter(prime(_)).foreach { i =>
    (i*i until LIMIT by i).foreach(prime(_) = false)
  }
  val primes = prime.indices.filter(prime(_)).take(n + 1)

  println(primes.drop(1).mkString(" "))
}

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

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

  out.println(List.range(10000000 - sc.nextInt, 10000000).mkString(" "))
  out.close
}

import java.util.Scanner
import scala.math._
import scala.collection.mutable.ListBuffer

object R327_B extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()

  println(answer(n).mkString(" "))

  def answer(n:Int):Seq[Int] = {
    var list = new ListBuffer[Int]()
    var s = 10000000 - n + 1
    list.append(s)
    while(s < 10000000){
      s += 1
      list.append(s)
    }
    //println(list)
    list
  }

}

import java.io._
import java.util.Locale
import scala.annotation.tailrec

object Easy {
  val reader = new BufferedReader(new InputStreamReader(System.in))
  def readInt = reader.readLine().toInt
  def readInts = reader.readLine().split(" ").map(_.toInt)
  def readLongs = reader.readLine().split(" ").map(_.toLong)

  val max = 10 * 1000 * 1000
  def ans = (max to max - readInt + 1 by -1).reverse.mkString(" ")

  def main(a: Array[String]) {
    println(ans)
  }
}

object Main {
  def sieveOfEratosthenes(nTo: Int) = {
    val primes = collection.mutable.BitSet.empty ++ (2 to nTo)
    for {
      candidate <- 2 until Math.sqrt(nTo).toInt
      if primes contains candidate
    } primes --= candidate * candidate to nTo by candidate
    primes
  }

  val simple0 = sieveOfEratosthenes(1299709)

  def main(args: Array[String]) {
    val n = readInt()
    println(simple0.take(n).mkString(" "))
  }
}

object Hungry {
    def main(args:Array[String]){
      val n=readInt
      n until 2*n foreach(x=>print(x+" "))
    }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val array = Array.ofDim[Boolean](1000002)
  array(0) = true
  array(1) = true
  (2 to 1000001).foreach { i =>
    if (!array(i)) {
      var j = 2 * i
      while (j <= 1000001) {
        array(j) = true
        j += i
      }
    }
  }
  println(array.indices.filter(i => !array(i)).take(n).mkString(" "))
}

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

object P327B extends App {

  object PrimeNumber {
    def apply(n: Int = 1000000): Array[Int] = sieve(n)

    def sieve(n: Int): Array[Int] = {
      val primes = new ArrayBuffer[Int]
      val isPrime = Array.fill(n + 1)(true)

      @tailrec
      def loop(i: Int): Unit = {

        @tailrec
        def innerLoop(j: Int): Unit = {
          if (j > n) ()
          else {
            isPrime(j) = false
            innerLoop(j + i)
          }
        }

        if (i > n) ()
        else {
          if (isPrime(i)) {
            primes += i
            innerLoop(i * 2)
          }
          loop(i + 1)
        }
      }

      loop(2)
      primes.toArray
    }
  }

  val sc = new Scanner(System.in)
  val out = new PrintWriter(System.out)
  out.println(PrimeNumber(1000000).take(sc.nextInt).mkString(" "))
  out.close
}

import java.util.Scanner
import scala.math._
import scala.collection.mutable.ListBuffer

object R327_B extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()

  println(answer(n).mkString(" "))

  def answer(n:Int):Seq[Int] = {
    var list = new ListBuffer[Int]()
    var s = 10000000 - n
    list.append(s)
    while(s < 10000000){
      s += 1
      list.append(s)
    }
    //println(s)
    list
  }

}

import java.util.Scanner
import scala.math._
import scala.collection.mutable.ListBuffer

object R327_B extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()

  println(answer(n).mkString(" "))

  def answer(n:Int):Seq[Int] = {
    var list = new ListBuffer[Int]()
    var c = 10000000
    var s = 10000000 - n
    list.append(c)
    while(s < 10000000){
      s += 1
      list.append(s)
    }
    list
  }

}

import java.util.Scanner
import scala.math._
import scala.collection.mutable.ListBuffer

object R327_B extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt()

  println(answer(n).mkString(" "))

  def answer(n:Int):Seq[Int] = {
    var list = new ListBuffer[Int]()
    var c = 10000000
    list.append(c)
    while(list.size < n){
      c -= 1
      //if(!list.exists(_ % c == 0)){
        list.append(n)
      //}else{
      //  println(c)
      //}
    }
    list.reverse
  }

}


Acacius is studying strings theory. Today he came with the following problem.You are given a string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks. It is possible to replace question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once?Each question mark should be replaced with exactly one lowercase English letter. For example, string "a?b?c" can be transformed into strings "aabbc" and "azbzc", but can't be transformed into strings "aabc", "a?bbc" and "babbc".Occurrence of a string $$$t$$$ of length $$$m$$$ in the string $$$s$$$ of length $$$n$$$ as a substring is a index $$$i$$$ ($$$1 \leq i \leq n - m + 1$$$) such that string $$$s[i..i+m-1]$$$ consisting of $$$m$$$ consecutive symbols of $$$s$$$ starting from $$$i$$$-th equals to string $$$t$$$. For example string "ababa" has two occurrences of a string "aba" as a substring with $$$i = 1$$$ and $$$i = 3$$$, but there are no occurrences of a string "aba" in the string "acba" as a substring.Please help Acacius to check if it is possible to replace all question marks with lowercase English letters in such a way that a string "abacaba" occurs as a substring in a resulting string exactly once.

First line of input contains an integer $$$T$$$ ($$$1 \leq T \leq 5000$$$), number of test cases. $$$T$$$ pairs of lines with test case descriptions follow. The first line of a test case description contains a single integer $$$n$$$ ($$$7 \leq n \leq 50$$$), length of a string $$$s$$$. The second line of a test case description contains string $$$s$$$ of length $$$n$$$ consisting of lowercase English letters and question marks.

For each test case output an answer for it. In case if there is no way to replace question marks in string $$$s$$$ with a lowercase English letters in such a way that there is exactly one occurrence of a string "abacaba" in the resulting string as a substring output "No". Otherwise output "Yes" and in the next line output a resulting string consisting of $$$n$$$ lowercase English letters. If there are multiple possible strings, output any. You may print every letter in "Yes" and "No" in any case you want (so, for example, the strings yEs, yes, Yes, and YES will all be recognized as positive answer).

6
7
abacaba
7
???????
11
aba?abacaba
11
abacaba?aba
15
asdf???f???qwer
11
abacabacaba

Yes
abacaba
Yes
abacaba
Yes
abadabacaba
Yes
abacabadaba
No
No

NoteIn first example there is exactly one occurrence of a string "abacaba" in the string "abacaba" as a substring.In second example seven question marks can be replaced with any seven lowercase English letters and with "abacaba" in particular.In sixth example there are two occurrences of a string "abacaba" as a substring.

object A {import InOut._
  def main(args: Array[String]): Unit = {
val target = "abacaba"
    for (_ <- 1 to nextInt) {
      val n = nextInt
      val s = nextLine

      val candidates = s.sliding(target.length).toArray
      val poss = candidates.indices.filter {
        p =>
          val c = candidates(p)
          var ok = true
          for (i <- 0 until target.length) {
            if (c(i) != '?' && c(i) != target(i)) {
              ok = false
            }
          }
          ok
      }

      var res = ""

      for (pos <- poss) {
        val c = candidates(pos)
        val s2 = s.take(pos) + target + s.drop(pos + target.length)
        val p1 = s2.indexOf(target)
        val p2 = s2.lastIndexOf(target)
//        println(pos, s2, p1, p2)
        if (p1 == p2) res = s2
      }

      if (res == "") {
        out.println("No")
      } else {
        out.println("Yes")
        out.println(res.replace('?', 'd'))
      }
    }

    out.flush()
  }

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

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

  val target = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    def check(from: Int): Boolean = {
      val sm = sn.slice(from, from + 7)

      if (sm.corresponds(target) { case ('?', _) => true; case (x, y) => x == y }) {
        val kn = sn.patch(from, target, target.length)
        kn.indexOfSlice(target) == kn.lastIndexOfSlice(target)
      } else false
    }

    val ans = (0 until n).collectFirst { case i if check(i) => i }

    ans match {
      case None => println("NO")
      case Some(i) =>
        val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }
        println("YES")
        println(res)
    }
  }
}

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

  val target = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    def check(from: Int): Boolean = {
      val kn = sn.patch(from, target, target.length)
      kn.indexOfSlice(target) == kn.lastIndexOfSlice(target)
    }

    val ans = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(target) { case ('?', _) => true; case (x, y) => x == y } => i
      }
      .collectFirst {
        case from if check(from) => from
      }

    ans match {
      case None => println("NO")
      case Some(i) =>
        val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }
        println("YES")
        println(res)
    }
  }
}

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

  val target = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    def check(from: Int): Boolean = {
      val sm = sn.slice(from, from + 7)

      if (sm.corresponds(target) { case ('?', _) => true; case (x, y) => x == y }) {
        val kn = sn.patch(from, target, target.length)
        kn.indexOfSlice(target, 0.max(from - 7)) == kn.lastIndexOfSlice(target, n.max(from + 7))
      } else false
    }

    val ans = (0 until n).collectFirst { case i if check(i) => i }

    ans match {
      case None => println("NO")
      case Some(i) =>
        val res = sn.patch(i, target, target.length).map { case '?' => 'd'; case c => c }
        println("YES")
        println(res)
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val ls = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          Some((s.indices.collect { case j if s(j) == '?' => i + j + 2 * abc(j) }.toList, i))
      }
      .toStream

    val l = ls match {
      case Stream() => None
      case _ =>
        ls.reduce[Option[(List[Int], Int)]] {
          case (None, Some(l))                  => Some(l)
          case (Some((Nil, _)), Some((Nil, _))) => None
          case (Some((Nil, i)), _)              => Some(Nil, i)
          case (_, Some((Nil, i)))              => Some(Nil, i)
          case (Some((is, i)), Some((js, j))) =>
            if (is.length > js.length) Some((js, j))
            else if (js.length > is.length) Some((is, i))
            else if (is.containsSlice(js)) None
            else Some((is, i))
        }
    }

    // format: off
    val ans = l.map { case (_, i) =>
      sn.zipWithIndex.map {
        case (_, j) if i <= j && j <= i + 6 => abc(j - i)
        case ('?', _)                       => 'd'
        case (c, _)                         => c
      }.mkString("")
    }
    // format: on

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val ans = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          (s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i)
      } // format: off
      .reduceOption[(List[Int], Int)] {
        case ((_, -1), _) | (_, (_, -1)) => (Nil, -1)
        case ((Nil, _), (Nil, _))        => (Nil, -1)
        case ((Nil, l), _)               => (Nil, l)
        case (_, (Nil, r))               => (Nil, r)
        case ((ls, l), (rs, r))          =>
          if (ls.containsSlice(rs)) {
            if (ls.length > rs.length) (rs, r)
            else if (ls.length < rs.length) (ls, l)
            else (Nil, -1)
          } else (ls, l)
      }
      .flatMap {
        case (_, -1) => None
        case (_, i)  =>
          val res = sn.zipWithIndex.map {
            case (_, j) if i <= j && j <= i + 6 => abc(j - i)
            case ('?', _)                       => 'd'
            case (c, _)                         => c
          }.mkString("")

          Some(res)
      } // format: on

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val rs = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          (s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i)
      }
      .toSeq

    val r = rs.foldLeft[Either[Option[String], (List[Int], Int)]](Left(Some("ok"))) {
      case (x @ Left(None), _)         => x
      case (Left(_), x)                => Right(x)
      case (Right((Nil, _)), (Nil, _)) => Left(None)
      case (x @ Right((Nil, _)), _)    => x
      case (_, x @ (Nil, _))           => Right(x)
      case (x @ Right((rs, r)), y @ (ls, l)) =>
        if (rs.length < ls.length) x
        else if (ls.length < rs.last) Right(y)
        else if (rs.containsSlice(ls)) Left(Some("ok"))
        else x

    }

    val ans = r match {
      case Left(_) => None
      case Right((_, i)) =>
        val res = sn.zipWithIndex
          .map {
            case (_, j) if i <= j && j <= i + 6 => abc(j - i)
            case ('?', _)                       => 'd'
            case (c, _)                         => c
          }
          .mkString("")

        Some(res)
    }

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val ls = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          Some((s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i))
      }
      .toStream

    val l = ls match {
      case Stream() => None
      case _ =>
        ls.reduce[Option[(List[Int], Int)]] {
          case (None, Some(l))                  => Some(l)
          case (Some((Nil, _)), Some((Nil, _))) => None
          case (Some((Nil, i)), _)              => Some(Nil, i)
          case (_, Some((Nil, i)))              => Some(Nil, i)
          case (Some((is, _)), Some((js, j)))   =>
            if (is.containsSlice(js) || js.containsSlice(is)) None else Some((js, j))
        }
    }

    val ans = l.map {
      case (_, i) =>
        sn.zipWithIndex
          .map {
            case (_, j) if i <= j && j <= i + 6 => abc(j - i)
            case ('?', _)                       => 'd'
            case (c, _)                         => c
          }
          .mkString("")
    }

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val ls = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          Some((s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i))
      }
      .toSeq

    val status = ls match {
      case Stream() => None
      case _ =>
        ls.reduce[Option[(List[Int], Int)]] {
          case (None, Some(l))                  => Some(l)
          case (Some((Nil, _)), Some((Nil, _))) => None
          case (Some((Nil, i)), _)              => Some(Nil, i)
          case (_, Some((Nil, i)))              => Some(Nil, i)
          case (Some((is, _)), Some((js, j)))   => if (is.containsSlice(js)) None else Some((js, j))
        }
    }

    val ans = status.map {
      case (_, i) =>
        sn.zipWithIndex
          .map {
            case (_, j) if i <= j && j <= i + 6 => abc(j - i)
            case ('?', _)                       => 'd'
            case (c, _)                         => c
          }
          .mkString("")
    }

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val ls = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          Some((s.indices.collect { case j if s(j) == '?' => i + j + abc(j) }.toList, i))
      }
      .toStream

    val l = ls match {
      case Stream() => None
      case _ =>
        ls.reduce[Option[(List[Int], Int)]] {
          case (None, Some(l))                  => Some(l)
          case (Some((Nil, _)), Some((Nil, _))) => None
          case (Some((Nil, i)), _)              => Some(Nil, i)
          case (_, Some((Nil, i)))              => Some(Nil, i)
          case (Some((is, i)), Some((js, j))) =>
            if (is.length > js.length) Some((js, j))
            else if (js.length > is.length) Some((is, i))
            else if (is.containsSlice(js)) None
            else Some((is, i))
        }
    }

    val ans = l.map {
      case (_, i) =>
        sn.zipWithIndex
          .map {
            case (_, j) if i <= j && j <= i + 6 => abc(j - i)
            case ('?', _)                       => 'd'
            case (c, _)                         => c
          }
          .mkString("")
    }

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}

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

  val abc = "abacaba"

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readInt()
    val sn = readLine()

    val ls = sn
      .sliding(7, 1)
      .zipWithIndex
      .collect {
        case (s, i) if s.corresponds(abc) { case ('?', _) => true; case (x, y) => x == y } =>
          Some((s.indices.collect { case j if s(j) == '?' => i + j + 2 * abc(j) }.toList, i))
      }
      .toStream

    val status = ls match {
      case Stream() => None
      case _ =>
        ls.reduce[Option[(List[Int], Int)]] {
          case (None, Some(l))                  => Some(l)
          case (Some((Nil, _)), Some((Nil, _))) => None
          case (Some((Nil, i)), _)              => Some(Nil, i)
          case (_, Some((Nil, i)))              => Some(Nil, i)
          case (Some((is, _)), Some((js, j)))   => if (is.containsSlice(js)) None else Some((js, j))
        }
    }

    val ans = status.map {
      case (_, i) =>
        sn.zipWithIndex
          .map {
            case (_, j) if i <= j && j <= i + 6 => abc(j - i)
            case ('?', _)                       => 'd'
            case (c, _)                         => c
          }
          .mkString("")
    }

    ans match {
      case None        => println("NO")
      case Some(value) => println(s"YES\n$value")
    }
  }
}


Bob has a favorite number k and ai of length n. Now he asks you to answer m queries. Each query is given by a pair li and ri and asks you to count the number of pairs of integers i and j, such that l ≤ i ≤ j ≤ r and the xor of the numbers ai, ai + 1, ..., aj is equal to k.

The first line of the input contains integers n, m and k (1 ≤ n, m ≤ 100 000, 0 ≤ k ≤ 1 000 000) — the length of the array, the number of queries and Bob's favorite number respectively. The second line contains n integers ai (0 ≤ ai ≤ 1 000 000) — Bob's array. Then m lines follow. The i-th line contains integers li and ri (1 ≤ li ≤ ri ≤ n) — the parameters of the i-th query.

Print m lines, answer the queries in the order they appear in the input.

NoteIn the first sample the suitable pairs of i and j for the first query are: (1, 2), (1, 4), (1, 5), (2, 3), (3, 6), (5, 6), (6, 6). Not a single of these pairs is suitable for the second query.In the second sample xor equals 1 for all subarrays of an odd length.

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 600
  def main(args: Array[String]) {
    val start = System.currentTimeMillis()
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt).scan(0)((x, y) => x ^ y)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      qs(i) = Query(l - 1, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = 0
    var s = 0L
    val ct = Array.fill(V)(0)
    ct(0) += 1
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        ct(a(q)) += 1
        s += ct(a(q) ^ k)
      }
      while (p > l) {
        p -= 1
        ct(a(p)) += 1
        s += ct(a(p) ^ k)
      }
      while (q > r) {
        s -= ct(a(q) ^ k)
        ct(a(q)) -= 1
        q -= 1
      }
      while (p < l) {
        s -= ct(a(p) ^ k)
        ct(a(p)) -= 1
        p += 1
      }
      ans(i) = s - (if (k == 0) (r - l) else 0)
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 600
  def main(args: Array[String]) {
    val start = System.currentTimeMillis()
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt).scan(0)((x, y) => x ^ y)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      qs(i) = Query(l - 1, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = 0
    var s = 0L
    val ct = Array.fill(V)(0)
    ct(0) += 1
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        s += ct(a(q) ^ k)
        ct(a(q)) += 1
      }
      while (p > l) {
        p -= 1
        s += ct(a(p) ^ k)
        ct(a(p)) += 1
      }
      while (q > r) {
        ct(a(q)) -= 1
        s -= ct(a(q) ^ k)
        q -= 1
      }
      while (p < l) {
        ct(a(p)) -= 1
        s -= ct(a(p) ^ k)
        p += 1
      }
      ans(i) = s
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 300
  def main(args: Array[String]) {
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt - 1)
      qs(i) = Query(l, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = -1
    var ls, rs = 0
    var s = 0L
    val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)
    ct(0) = 1
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        rs ^= a(q)
        ct(rs) += 1
        s += ct(rs ^ k)
      }
      while (p > l) {
        p -= 1
        ls ^= a(p)
        ct(ls) += 1
        s += ct(ls ^ k)
      }
      while (q > r) {
        s -= ct(rs ^ k)
        ct(rs) -= 1
        rs ^= a(q)
        q -= 1
      }
      while (p < l) {
        s -= ct(ls ^ k)
        ct(ls) -= 1
        ls ^= a(p)
        p += 1
      }
      ans(i) = s
      println(i, s)
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 300
  def main(args: Array[String]) {
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt).scan(0)((x, y) => x ^ y)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      qs(i) = Query(l - 1, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = 0
    var s = 0L
    val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        ct(a(q)) += 1
        s += ct(a(q) ^ k)
      }
      while (p > l) {
        p -= 1
        ct(a(p)) += 1
        s += ct(a(p) ^ k)
      }
      while (q > r) {
        s -= ct(a(q) ^ k)
        ct(a(q)) -= 1
        q -= 1
      }
      while (p < l) {
        s -= ct(a(p) ^ k)
        ct(a(p)) -= 1
        p += 1
      }
      ans(i) = s
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 300
  def main(args: Array[String]) {
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt - 1)
      qs(i) = Query(l, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = -1
    var ls, rs = 0
    var s = 0L
    val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)
    ct(0) = 1
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        rs ^= a(q)
        ct(rs) += 1
        s += ct(rs ^ k)
      }
      while (p > l) {
        p -= 1
        ls ^= a(p)
        ct(ls) += 1
        s += ct(ls ^ k)
      }
      while (q > r) {
        s -= ct(rs ^ k)
        ct(rs) -= 1
        rs ^= a(q)
        q -= 1
      }
      while (p < l) {
        s -= ct(ls ^ k)
        ct(ls) -= 1
        ls ^= a(p)
        p += 1
      }
      ans(i) = s
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 300
  def main(args: Array[String]) {
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt).scan(0)((x, y) => x ^ y)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)
      qs(i) = Query(l - 1, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = 0
    var s = 0L
    val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)
    ct(0) = 1
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        ct(a(q)) += 1
        s += ct(a(q) ^ k)
      }
      while (p > l) {
        p -= 1
        ct(a(p)) += 1
        s += ct(a(p) ^ k)
      }
      while (q > r) {
        s -= ct(a(q) ^ k)
        ct(a(q)) -= 1
        q -= 1
      }
      while (p < l) {
        s -= ct(a(p) ^ k)
        ct(a(p)) -= 1
        p += 1
      }
      ans(i) = s
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}

import scala.io.StdIn

object Main {
  final val V = 1 << 20;
  def main(args: Array[String]) {
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val qs = Array.fill(m)((0, 0))
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt - 1)
      qs(i) = (l, r)
    }
    val ctl, ctr = Array.fill(n)(0L)
    val tbl = Array.fill(V)(0L)
    val sum = Array.fill(n)(0)
    tbl(0) = 1
    var s = 0L
    var t = 0
    for (i <- 0 until n) {
      t ^= a(i)
      sum(i) = t
      ctr(i) = tbl(t ^ k)
      s += tbl(t ^ k)
      tbl(t) += 1
    }
    for (i <- 0 until V) tbl(i) = 0
    t = 0
    tbl(0) = 1
    for (i <- n - 1 to 0 by -1) {
      t ^= a(i)
      ctl(i) = tbl(t ^ k)
      tbl(t) += 1
    }
    for (i <- 1 until n) {
      ctl(i) += ctl(i - 1)
    }
    for (i <- n - 2 to 0 by -1) {
      ctr(i) += ctr(i + 1)
    }
    val ans = Array.fill(m)(0L)
    for (((l, r), i) <- qs.zipWithIndex) {
      ans(i) = s
      if (l > 0) ans(i) -= ctl(l - 1)
      if (r < n - 1) ans(i) -= ctr(r + 1)
      if (l > 0) ans(i) += (if ((sum(r) ^ sum(l - 1)) == k) 1L else 0L)
    }
    println(ans.mkString("\n"))
  }
}

import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer
import scala.io.StdIn
import scala.util.Sorting

object Main {
  final val V = 1 << 20;
  final val B = 300
  def main(args: Array[String]) {
    val Array(n, m, k) = StdIn.readLine().split(" ").map(_.toInt)
    val a = StdIn.readLine().split(" ").map(_.toInt)
    val qs = new Array[Query](m)
    for (i <- 0 until m) {
      val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt - 1)
      qs(i) = Query(l, r, i)
    }
    Sorting.quickSort(qs)(new Ordering[Query] {
      override def compare(x: Query, y: Query): Int = {
        if (x.l / B != y.l / B) (x.l / B) compare (y.l / B) else (x.r) compare (y.r)
      }
    })
    val ans = Array.fill(m)(0L)
    var p = 0
    var q = -1
    var ls, rs = 0
    var s = 0L
    val ct = mutable.HashMap[Int, Long]().withDefault(_ => 0)
    ct(0) = 1
    for (Query(l, r, i) <- qs) {
      while (q < r) {
        q += 1
        rs ^= a(q)
        ct(rs) += 1
        s += ct(rs ^ k)
      }
      while (p > l) {
        ls ^= a(p)
        p -= 1
        ct(ls) += 1
        s += ct(ls ^ k)
      }
      while (q > r) {
        s -= ct(rs ^ k)
        ct(rs) -= 1
        rs ^= a(q)
        q -= 1
      }
      while (p < l) {
        s -= ct(ls ^ k)
        ct(ls) -= 1
        p += 1
        ls ^= a(p)
      }
      ans(i) = s
    }
    println(ans.mkString("\n"))
  }
  case class Query(val l: Int, val r: Int, val i: Int) {}
}


Musicians of a popular band "Flayer" have announced that they are going to "make their exit" with a world tour. Of course, they will visit Berland as well.There are n cities in Berland. People can travel between cities using two-directional train routes; there are exactly m routes, i-th route can be used to go from city vi to city ui (and from ui to vi), and it costs wi coins to use this route.Each city will be visited by "Flayer", and the cost of the concert ticket in i-th city is ai coins.You have friends in every city of Berland, and they, knowing about your programming skills, asked you to calculate the minimum possible number of coins they have to pay to visit the concert. For every city i you have to compute the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).Formally, for every  you have to calculate , where d(i, j) is the minimum number of coins you have to spend to travel from city i to city j. If there is no way to reach city j from city i, then we consider d(i, j) to be infinitely large.

The first line contains two integers n and m (2 ≤ n ≤ 2·105, 1 ≤ m ≤ 2·105). Then m lines follow, i-th contains three integers vi, ui and wi (1 ≤ vi, ui ≤ n, vi ≠ ui, 1 ≤ wi ≤ 1012) denoting i-th train route. There are no multiple train routes connecting the same pair of cities, that is, for each (v, u) neither extra (v, u) nor (u, v) present in input. The next line contains n integers a1, a2, ... ak (1 ≤ ai ≤ 1012) — price to attend the concert in i-th city.

Print n integers. i-th of them must be equal to the minimum number of coins a person from city i has to spend to travel to some city j (or possibly stay in city i), attend a concert there, and return to city i (if j ≠ i).

import java.util

import D.as

import scala.collection.mutable

object D extends App {

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

  val Array(n, m) = readInts(2)

  case class Route(u: Int, v: Int, w: Long)

  val adjBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofInt }
  val wBuilders = Array.fill(n){ new mutable.ArrayBuilder.ofLong }

  for (i <- 0 until m) {
    val Array(_u, _v, w) = readLongs(3)
    val u = _u.toInt - 1
    val v = _v.toInt - 1
    adjBuilders(u) += v
    wBuilders(u) += w
    adjBuilders(v) += u
    wBuilders(v) += w
  }

  val adjs = adjBuilders.map(_.result())
  val ws = wBuilders.map(_.result())

  val as = readLongs(n)

  val changed = new util.ArrayDeque[Int]
  for (u <- (0 until n).sortBy(as)) changed.add(u)
  val inChanged = Array.fill(n){ true }

  while (!changed.isEmpty) {
    val u = changed.poll()
    inChanged(u) = false
    var i = 0
    while (i < adjs(u).length) {
      val v = adjs(u)(i)
      val w = ws(u)(i)
      val c = as(u) + 2 * w
      if (c < as(v)) {
        as(v) = c
        if (!inChanged(v)) {
          changed.add(v)
          inChanged(v) = true
        }
      }
      i += 1
    }
  }

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

  println(as.mkString(" "))

  Console.flush
}


Max wants to buy a new skateboard. He has calculated the amount of money that is needed to buy a new skateboard. He left a calculator on the floor and went to ask some money from his parents. Meanwhile his little brother Yusuf came and started to press the keys randomly. Unfortunately Max has forgotten the number which he had calculated. The only thing he knows is that the number is divisible by 4.You are given a string s consisting of digits (the number on the display of the calculator after Yusuf randomly pressed the keys). Your task is to find the number of substrings which are divisible by 4. A substring can start with a zero.A substring of a string is a nonempty sequence of consecutive characters.For example if string s is 124 then we have four substrings that are divisible by 4: 12, 4, 24 and 124. For the string 04 the answer is three: 0, 4, 04.As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

The only line contains string s (1 ≤ |s| ≤ 3·105). The string s contains only digits from 0 to 9.

Print integer a — the number of substrings of the string s that are divisible by 4. Note that the answer can be huge, so you should use 64-bit integer type to store it. In C++ you can use the long long integer type and in Java you can use long integer type.

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val str = in.next()
  val singleChar = str.count(i => i == '4' || i == '8' || i == '0')
  val otherSubstrings =
    if (str.length == 1) 0
    else {
      str.indices.tail.foldLeft(0l) {
        case (acc, i) =>
          val number = str(i - 1).asDigit * 10 + str(i).asDigit
          if (number % 4 == 0)
            acc + i
          else acc
      }
    }
  println(singleChar + otherSubstrings)
}


Ivan wants to play a game with you. He picked some string $$$s$$$ of length $$$n$$$ consisting only of lowercase Latin letters. You don't know this string. Ivan has informed you about all its improper prefixes and suffixes (i.e. prefixes and suffixes of lengths from $$$1$$$ to $$$n-1$$$), but he didn't tell you which strings are prefixes and which are suffixes.Ivan wants you to guess which of the given $$$2n-2$$$ strings are prefixes of the given string and which are suffixes. It may be impossible to guess the string Ivan picked (since multiple strings may give the same set of suffixes and prefixes), but Ivan will accept your answer if there is at least one string that is consistent with it. Let the game begin!

The first line of the input contains one integer number $$$n$$$ ($$$2 \le n \le 100$$$) — the length of the guessed string $$$s$$$. The next $$$2n-2$$$ lines are contain prefixes and suffixes, one per line. Each of them is the string of length from $$$1$$$ to $$$n-1$$$ consisting only of lowercase Latin letters. They can be given in arbitrary order. It is guaranteed that there are exactly $$$2$$$ strings of each length from $$$1$$$ to $$$n-1$$$. It is also guaranteed that these strings are prefixes and suffixes of some existing string of length $$$n$$$.

Print one string of length $$$2n-2$$$ — the string consisting only of characters 'P' and 'S'. The number of characters 'P' should be equal to the number of characters 'S'. The $$$i$$$-th character of this string should be 'P' if the $$$i$$$-th of the input strings is the prefix and 'S' otherwise. If there are several possible answers, you can print any.

NoteThe only string which Ivan can guess in the first example is "ababa".The only string which Ivan can guess in the second example is "aaa". Answers "SPSP", "SSPP" and "PSPS" are also acceptable.In the third example Ivan can guess the string "ac" or the string "ca". The answer "SP" is also acceptable.

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = map(2 * N - 2) { _ => ns() }

    val grouped = S.zipWithIndex.groupBy(_._1.length)
    val ans = Array.ofDim[Char](S.length)
    def make(len: Int, prefix: String, suffix: String): Boolean = {
      if (len == 0) true
      else {
        val Array((s1, i1), (s2, i2)) = grouped(len)

        if (prefix.startsWith(s1) && suffix.endsWith(s2)) {
          ans(i1) = 'P'
          ans(i2) = 'S'
          make(len - 1, prefix, suffix)

        } else if (prefix.startsWith(s2) && suffix.endsWith(s1)) {
          ans(i1) = 'S'
          ans(i2) = 'P'
          make(len - 1, prefix, suffix)

        } else {
          // この割り振りは間違っていた
          false
        }
      }
    }

    val s1 = grouped(N - 1)(0)._1
    val s2 = grouped(N - 1)(1)._1
    if (make(N - 1, s1, s2)) {
      out.println(ans.mkString)
    } else {
      make(N - 1, s2, s1)
      out.println(ans.mkString)
    }
  }

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

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

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

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

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

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

object CF_527_3_C {
  def solve(n: Int, ss: Seq[String]): String = {
    val pairs: Map[Int, Seq[(String, Int)]] = ss.zipWithIndex.groupBy(_._1.length)
    // Strategy: Look at longest two to give 2 possible strings
    val possibles: Seq[String] = pairs(n - 1) match {
      case Seq((a, _), (b, _)) => Seq(a + b.last, b + a.last)
    }

    //
    def isPrefix(pre: String, s: String) = s.take(pre.length) == pre

    def isSuffix(suff: String, s: String) = s.takeRight(suff.length) == suff

    // Seqs of values starting from longest
    val strs: Seq[Seq[(String, Int)]] = pairs.values.toSeq

    def isValid(test: String, ps: Seq[Seq[(String, Int)]], out: Seq[(String, Int)]): Option[Seq[(String, Int)]] = ps match {
      case Seq() => Some(out)
      case Seq((n1, i), (n2, j)) +: tail =>
        if (isPrefix(n1, test) && isSuffix(n2, test)) isValid(test, tail, out :+ ("P", i) :+ ("S", j))
        else if (isPrefix(n2, test) && isSuffix(n1, test))
          isValid(test, tail, out :+ ("S", i) :+ ("P", j))
        else None
    }

    val result: String = possibles.map(p => isValid(p, strs, Nil)).find(_.isDefined).get.get.sortBy(_._2).map(_._1).mkString

    result
  }

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

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

//     ~~~ Boilerplate & utility methods that don't change: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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

  import java.util.Scanner
  class Input(sc: Scanner) {
    def this(i: java.io.InputStream) = this(new Scanner(i))
    def this(s: String) = this(new Scanner(s.stripMargin))
    def int = sc.nextInt()
    def long = sc.nextLong()
    def double = sc.nextDouble()
    def nextLine = sc.nextLine()
    // Remember to call nextLine to advance past the newline character (if required) before collecting the line:
    def collect[T](f: String => T) = {sc.nextLine().split(" ").toVector.map(f)}
    def intSeq = collect(_.toInt)
    def doubleSeq = collect(_.toDouble)
    def getLines: Vector[String] = if (!sc.hasNextLine) Vector.empty else sc.nextLine +: getLines
    def solveVal = (solve _).tupled(formatIn(this))
    def solveStr = formatOut(solveVal)
  }

  def ceil(a: Int, b: Int) = (a - 1) / b + 1
  def ceil(a: Long, b: Long) = (a - 1) / b + 1
  val modulo = 1000000007

  import language.implicitConversions
  implicit def stringToInput(s: String): Input = new Input(s)
  implicit class makeTupledWorkOnFunction1[-T,+R](f: T => R) { def tupled: T => R = x => f(x) }
}

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = map(2 * N - 2) { _ => ns() }
    val sorted = S.sorted

    def mkPrefix(S1: Array[String]) = {
      var ok = true
      var ix = 0
      REP(S1.length - 1) { i =>
        ok &&= S1(i + 1).startsWith(S1(i))
        if (ok) ix = i
      }
      S1(ix + 1)
    }

    val prefix = mkPrefix(Array("") ++ sorted)
//    val suffix = mkPrefix(Array("") ++ sorted.reverse)

    val cnt = Array.ofDim[Int](N)

    val ans = map(S.length) { i =>
      if (prefix.startsWith(S(i))) {
        cnt(S(i).length) += 1
        if (cnt(S(i).length) == 1) 'P'
        else 'S'
      } else 'S'
    }.mkString

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = map(2 * N - 2) { _ => ns() }
    val S1 = "" +: S
    Sorting.quickSort(S1)

    var ok = true
    var ix = 0
    REP(S1.length - 1) { i =>
      ok &&= S1(i + 1).startsWith(S1(i))
      if (ok) ix = i
    }
    val prefix = S1(ix + 1)
    val ans = map(S.length) { i =>
      if (prefix.startsWith(S(i))) 'P'
      else 'S'
    }.mkString

    out.println(ans)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = map(2 * N - 2) { _ => ns() }

    val grouped = S.zipWithIndex.groupBy(_._1.length)

    val prefix = grouped(N - 1)(0)._1
    val suffix = grouped(N - 1)(1)._1

    val ans = Array.ofDim[Char](S.length)
    grouped.foreach { case (_, as) =>
      val Array((s1, i1), (s2, i2)) = as
      if (prefix.startsWith(s1) && suffix.startsWith(s2)) {
        ans(i1) = 'P'
        ans(i2) = 'S'
      } else {
        ans(i2) = 'P'
        ans(i1) = 'S'
      }
    }

    out.println(ans.mkString)
  }

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

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

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

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

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

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

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

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

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

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

  def solve(): Unit = {
    val N = ni()
    val S = map(2 * N - 2) { _ => ns() }
    val sorted = S.sorted

    def mkPrefix(S1: Array[String]) = {
      var ok = true
      var ix = 0
      REP(S1.length - 1) { i =>
        ok &&= S1(i + 1).startsWith(S1(i))
        if (ok) ix = i
      }
      S1(ix + 1)
    }

    val prefix = mkPrefix(Array("") ++ sorted)
    val suffix = mkPrefix(Array("") ++ sorted.reverse)

    val grouped = S.zipWithIndex.groupBy(_._1.length)
    val ans = Array.ofDim[Char](S.length)
    grouped.foreach { case (_, as) =>
      val Array((s1, i1), (s2, i2)) = as
      if (prefix.startsWith(s1) && suffix.startsWith(s2)) {
        ans(i1) = 'P'
        ans(i2) = 'S'
      } else {
        ans(i2) = 'P'
        ans(i1) = 'S'
      }
    }

    out.println(ans.mkString)
  }

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

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

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

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

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

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