Tavas is a strange creature. Usually "zzz" comes out of people's mouth while sleeping, but string s of length n comes out from Tavas' mouth instead.  Today Tavas fell asleep in Malekas' place. While he was sleeping, Malekas did a little process on s. Malekas has a favorite string p. He determined all positions x1 < x2 < ... < xk where p matches s. More formally, for each xi (1 ≤ i ≤ k) he condition sxisxi + 1... sxi + |p| - 1 = p is fullfilled.Then Malekas wrote down one of subsequences of x1, x2, ... xk (possibly, he didn't write anything) on a piece of paper. Here a sequence b is a subsequence of sequence a if and only if we can turn a into b by removing some of its elements (maybe no one of them or all).After Tavas woke up, Malekas told him everything. He couldn't remember string s, but he knew that both p and s only contains lowercase English letters and also he had the subsequence he had written on that piece of paper.Tavas wonders, what is the number of possible values of s? He asked SaDDas, but he wasn't smart enough to solve this. So, Tavas asked you to calculate this number for him.Answer can be very large, so Tavas wants you to print the answer modulo 109 + 7.

The first line contains two integers n and m, the length of s and the length of the subsequence Malekas wrote down (1 ≤ n ≤ 106 and 0 ≤ m ≤ n - |p| + 1). The second line contains string p (1 ≤ |p| ≤ n). The next line contains m space separated integers y1, y2, ..., ym, Malekas' subsequence (1 ≤ y1 < y2 < ... < ym ≤ n - |p| + 1).

In a single line print the answer modulo 1000 000 007.

NoteIn the first sample test all strings of form "ioioi?" where the question mark replaces arbitrary English letter satisfy.Here |x| denotes the length of string x.Please note that it's possible that there is no such string (answer is 0).

import scala.collection._

object B extends App {

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

  val Array(n, m) = readInts(2)
  val p = readLine
  val ys = if (m == 0) Array.empty else readInts(m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length + 1) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }

  val d = p.length - next(p.length)

  var ok = true
  if (ys.nonEmpty) {
    var prev = ys.head
    for (y <- ys.tail) {
      if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false
      prev = y
    }
  }

  if (!ok) println(0)
  else {
    val occupied = mutable.BitSet.empty
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length - 1
      while (i <= r) {
        occupied += i
        i += 1
      }
      pos = r
    }
    val free = n - occupied.size
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

import scala.collection._

object B extends App {

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

  val Array(n, m) = readInts(2)
  val p = readLine
  val ys = if (m == 0) Array.empty else readInts(m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length + 1) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }

  val d = p.length - next(p.length)

  var ok = true
  if (ys.nonEmpty) {
    var prev = ys.head
    for (y <- ys.tail) {
      if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false
      prev = y
    }
  }

  if (!ok) println(0)
  else {
    var free = n
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length
      while (i < r) {
        free -= 1
        i += 1
      }
      pos = r
    }
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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)
  val p = readLine
  val ys = if (_m == 0) Array.empty else readInts(_m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length + 1) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }
  /*
  var j = 0
  val matchesBuilder = new ArrayBuilder.ofInt
  for (i <- p.indices) {
    while (j > 0 && p(j) != p(i)) j = next(j)
    if (p(j) == p(i)) j += 1
    println(i, j)
//    if (j == p.length - i) {
//      matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m
//      j = next(j)
//    }
    if (i == p.size - 1) println(j)
  }

  val matches = matchesBuilder.result
  val matchesSet = mutable.BitSet.empty ++ matches
  println(matches.mkString(" "))
  println(next.mkString(" "))
  if (!ys.forall(matchesSet)) println(0)
  */

  val d = p.length - next(p.length)
  //println(d)

  var ok = true
  if (ys.nonEmpty) {
    var prev = ys.head
    for (y <- ys.tail) {
      if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false
      prev = y
    }
  }

  if (!ok) println(0)
  else {
    val occupied = mutable.BitSet.empty
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length - 1
      while (i <= r) {
        occupied += i
        i += 1
      }
      pos = r
    }
    val free = n - occupied.size
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

object B extends App {

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

  val Array(n, m) = readInts(2)
  val p = readLine
  val ys = if (m == 0) Array.empty else readInts(m).map(_ - 1)

  val next = Array.fill(p.length + 1)(0)
  var k = 0
  for (j <- 1 until p.length) {
    while (k > 0 && p(k) != p(j)) k = next(k)
    if (p(k) == p(j)) k += 1
    next(j + 1) = k
  }

  val d = p.length - next(p.length)

  var ok = true
  if (ys.nonEmpty) {
    var prev = ys.head
    for (y <- ys.tail) {
      if ((y - prev) % d != 0 && y - prev < p.length) ok = false
      prev = y
    }
  }

  if (!ok) println(0)
  else {
    var free = n
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length
      while (i < r) {
        free -= 1
        i += 1
      }
      pos = r
    }
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

object D{
  def main(args: Array[String]){
//   import scala.collection.mutable.PriorityQueue
//    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable.BitSet
//    import scala.collection.mutable.Set
    import util.control.Breaks._
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    val n=in.nextInt
    val m=in.nextInt
    val sub=in.next
    val y=(for(i<- 0 until m) yield in.nextInt).toArray
    // index
/*    var A= collection.immutable.Set[Int]()
    for(k<- 1 to sub.length-1){
      A=A.filter((l)=>sub(k)==sub(k-l))

      if(sub(k)==sub(0)){
        A=A+k
      }
 }*/

    //    for(i<-0 until sub.length){out.print(A(i)+" ")}
    var sum=0

    var bad=false
    if(m!=0){
      var A=Array.fill(sub.length)(-1)
      var j= -1
      A(0)= -1
      for(i<-1 until sub.length){
        while(j>=0 && sub(i)!=sub(j+1)){
          j=A(j)
        }
        if(j== -1){
          if(sub(i)!=sub(0)){
            j= -2
          }
        }
        j+=1
        A(i)=j
      }
      sum=y(0)-1
      var B=Array.fill(sub.length)(true)
      var ll=sub.length-1
      ll=A(ll)
      while(ll>=0){
        B(sub.length-ll-1)=false
        ll=A(ll)
      }
      breakable{
        for(i<-1 until m){
          if(y(i)-y(i-1)>=sub.length){
            sum+=y(i)-y(i-1)-sub.length
          }
          else if(B(y(i)-y(i-1))){
            bad=true
            break
          }
        }
      }
    }
    if(m!=0 && n-y(m-1)+1<sub.length){
      bad=true
    }
    if(bad){
      out.println(0)
    }else{
      if(m==0){
        sum=n
      }else{
        sum+=n-y(m-1)-sub.length+1
      }
      var r=1L
      for(i<-0 until sum){
        r=(r*26L)%1000000007L
      }
      out.println(r)
    }

    out.flush
out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    val n=in.nextInt
    val m=in.nextInt
    val sub=in.next
//    nextLine
//    val y=(nextLine.split(' ').map((s)=>s.toInt)).toArray
    val y=Array.fill(m)(0)

    for(i<- 0 until m) {y(i)=nextInt}
    // index
/*    var A= collection.immutable.Set[Int]()
    for(k<- 1 to sub.length-1){
      A=A.filter((l)=>sub(k)==sub(k-l))

      if(sub(k)==sub(0)){
        A=A+k
      }
 }*/

    //    for(i<-0 until sub.length){out.print(A(i)+" ")}
    var sum=0

    var bad=false
    if(m!=0){
      val A=Array.fill(sub.length)(-1)
      var j= -1
      A(0)= -1
      for(i<-1 until sub.length){
        while(j>=0 && sub(i)!=sub(j+1)){
          j=A(j)
        }
        if(j== -1){
          if(sub(i)!=sub(0)){
            j= -2
          }
        }
        j+=1
        A(i)=j
      }
      sum=y(0)-1
      val B=Array.fill(sub.length)(true)
      var ll=sub.length-1
      ll=A(ll)
      while(ll>=0){
        B(sub.length-ll-1)=false
        ll=A(ll)
      }
      breakable{
        for(i<-1 until m){
          if(y(i)-y(i-1)>=sub.length){
            sum+=y(i)-y(i-1)-sub.length
          }
          else if(B(y(i)-y(i-1))){
            bad=true
            break
          }
        }
      }
    }
    if(m!=0 && n-y(m-1)+1<sub.length){
      bad=true
    }
    if(bad){
      out.println(0)
    }else{
      if(m==0){
        sum=n
      }else{
        sum+=n-y(m-1)-sub.length+1
      }
      var r=1L
      for(i<-0 until sum){
        r=(r*26L)%1000000007L
      }
      out.println(r)
    }

    out.flush
out.close
  }
}

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

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

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

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

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    val n=in.nextInt
    val m=in.nextInt
    val sub=in.next
//    nextLine
//    val y=(nextLine.split(' ').map((s)=>s.toInt)).toArray
   // val y=Array.fill(m)(0)
    val y= (for(_<- 0 until m) yield nextInt).toArray
//    for(i<- 0 until m) {y(i)=nextInt}
    // index
/*    var A= collection.immutable.Set[Int]()
    for(k<- 1 to sub.length-1){
      A=A.filter((l)=>sub(k)==sub(k-l))

      if(sub(k)==sub(0)){
        A=A+k
      }
 }*/

    //    for(i<-0 until sub.length){out.print(A(i)+" ")}
    var sum=0

    var bad=false
    if(m!=0){
      val A=Array.fill(sub.length)(-1)
      var j= -1
      A(0)= -1
      for(i<-1 until sub.length){
        while(j>=0 && sub(i)!=sub(j+1)){
          j=A(j)
        }
        if(j== -1){
          if(sub(i)!=sub(0)){
            j= -2
          }
        }
        j+=1
        A(i)=j
      }
      sum=y(0)-1
      val B=Array.fill(sub.length)(true)
      var ll=sub.length-1
      ll=A(ll)
      while(ll>=0){
        B(sub.length-ll-1)=false
        ll=A(ll)
      }
      breakable{
        for(i<-1 until m){
          if(y(i)-y(i-1)>=sub.length){
            sum+=y(i)-y(i-1)-sub.length
          }
          else if(B(y(i)-y(i-1))){
            bad=true
            break
          }
        }
      }
    }
    if(m!=0 && n-y(m-1)+1<sub.length){
      bad=true
    }
    if(bad){
      out.println(0)
    }else{
      if(m==0){
        sum=n
      }else{
        sum+=n-y(m-1)-sub.length+1
      }
      var r=1L
      for(i<-0 until sum){
        r=(r*26L)%1000000007L
      }
      out.println(r)
    }

    out.flush
out.close
  }
}

object D{
  def main(args: Array[String]){
//   import scala.collection.mutable.PriorityQueue
//    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable.BitSet
//    import scala.collection.mutable.Set
    import util.control.Breaks._
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    def nextLine=in.nextLine
    val n=in.nextInt
    val m=in.nextInt
    val sub=in.next
//    nextLine
//    val y=(nextLine.split(' ').map((s)=>s.toInt)).toArray
    val y=(for(_<- 0 until m)yield nextInt).toArray
    // index
/*    var A= collection.immutable.Set[Int]()
    for(k<- 1 to sub.length-1){
      A=A.filter((l)=>sub(k)==sub(k-l))

      if(sub(k)==sub(0)){
        A=A+k
      }
 }*/

    //    for(i<-0 until sub.length){out.print(A(i)+" ")}
    var sum=0

    var bad=false
    if(m!=0){
      val A=Array.fill(sub.length)(-1)
      var j= -1
      A(0)= -1
      for(i<-1 until sub.length){
        while(j>=0 && sub(i)!=sub(j+1)){
          j=A(j)
        }
        if(j== -1){
          if(sub(i)!=sub(0)){
            j= -2
          }
        }
        j+=1
        A(i)=j
      }
      sum=y(0)-1
      val B=Array.fill(sub.length)(true)
      var ll=sub.length-1
      ll=A(ll)
      while(ll>=0){
        B(sub.length-ll-1)=false
        ll=A(ll)
      }
      breakable{
        for(i<-1 until m){
          if(y(i)-y(i-1)>=sub.length){
            sum+=y(i)-y(i-1)-sub.length
          }
          else if(B(y(i)-y(i-1))){
            bad=true
            break
          }
        }
      }
    }
    if(m!=0 && n-y(m-1)+1<sub.length){
      bad=true
    }
    if(bad){
      out.println(0)
    }else{
      if(m==0){
        sum=n
      }else{
        sum+=n-y(m-1)-sub.length+1
      }
      var r=1L
      for(i<-0 until sum){
        r=(r*26L)%1000000007L
      }
      out.println(r)
    }

    out.flush
out.close
  }
}

object D{
  //import scala.collection.mutable.PriorityQueue
  //import scala.collection.mutable.ArrayBuffer
  import util.control.Breaks._
  import java.io.{PrintWriter}
  import java.util.{Locale, Scanner}

  def main(args: Array[String]){

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    def nextLine=in.nextLine
    val n=in.nextInt
    val m=in.nextInt
    val sub=in.next
//    nextLine
//    val y=(nextLine.split(' ').map((s)=>s.toInt)).toArray
    val y=Array.fill(m)(0)

    for(i<- 0 until m) {y(i)=nextInt}
    // index
/*    var A= collection.immutable.Set[Int]()
    for(k<- 1 to sub.length-1){
      A=A.filter((l)=>sub(k)==sub(k-l))

      if(sub(k)==sub(0)){
        A=A+k
      }
 }*/

    //    for(i<-0 until sub.length){out.print(A(i)+" ")}
    var sum=0

    var bad=false
    if(m!=0){
      val A=Array.fill(sub.length)(-1)
      var j= -1
      A(0)= -1
      for(i<-1 until sub.length){
        while(j>=0 && sub(i)!=sub(j+1)){
          j=A(j)
        }
        if(j== -1){
          if(sub(i)!=sub(0)){
            j= -2
          }
        }
        j+=1
        A(i)=j
      }
      sum=y(0)-1
      val B=Array.fill(sub.length)(true)
      var ll=sub.length-1
      ll=A(ll)
      while(ll>=0){
        B(sub.length-ll-1)=false
        ll=A(ll)
      }
      breakable{
        for(i<-1 until m){
          if(y(i)-y(i-1)>=sub.length){
            sum+=y(i)-y(i-1)-sub.length
          }
          else if(B(y(i)-y(i-1))){
            bad=true
            break
          }
        }
      }
    }
    if(m!=0 && n-y(m-1)+1<sub.length){
      bad=true
    }
    if(bad){
      out.println(0)
    }else{
      if(m==0){
        sum=n
      }else{
        sum+=n-y(m-1)-sub.length+1
      }
      var r=1L
      for(i<-0 until sum){
        r=(r*26L)%1000000007L
      }
      out.println(r)
    }

    out.flush
out.close
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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)
  val p = readLine
  val ys = readInts(_m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length + 1) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }
/*
  var j = 0
  val matchesBuilder = new ArrayBuilder.ofInt
  for (i <- p.indices) {
    while (j > 0 && p(j) != p(i)) j = next(j)
    if (p(j) == p(i)) j += 1
    println(i, j)
//    if (j == p.length - i) {
//      matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m
//      j = next(j)
//    }
    if (i == p.size - 1) println(j)
  }

  val matches = matchesBuilder.result
  val matchesSet = mutable.BitSet.empty ++ matches
  println(matches.mkString(" "))
  println(next.mkString(" "))
  if (!ys.forall(matchesSet)) println(0)
  */

  val d = p.length - next(p.length)
  //println(d)

  var prev = ys.head
  var ok = true
  for (y <- ys.tail) {
    if ((y - prev) % d != 0) ok = false
    prev = y
  }

  if (!ok) println(0)
  else {
    val occupied = mutable.BitSet.empty
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length - 1
      while (i <= r) {
        occupied += i
        i += 1
      }
      pos = r
    }
    val free = n - occupied.size
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

object B extends App {

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

  val Array(n, m) = readInts(2)
  val p = readLine
  val ys = if (m == 0) Array.empty else readInts(m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length + 1) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }

  val d = p.length - next(p.length)

  var ok = true
  if (ys.nonEmpty) {
    var prev = ys.head
    for (y <- ys.tail) {
      if ((y - prev) % d != 0 && (y - prev < p.length)) ok = false
      prev = y
    }
  }

  if (!ok) println(0)
  else {
    var free = n
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length - 1
      while (i <= r) {
        free -= 1
        i += 1
      }
      pos = r
    }
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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)
  val p = readLine
  val ys = readInts(_m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length + 1) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }
  /*
  var j = 0
  val matchesBuilder = new ArrayBuilder.ofInt
  for (i <- p.indices) {
    while (j > 0 && p(j) != p(i)) j = next(j)
    if (p(j) == p(i)) j += 1
    println(i, j)
//    if (j == p.length - i) {
//      matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m
//      j = next(j)
//    }
    if (i == p.size - 1) println(j)
  }

  val matches = matchesBuilder.result
  val matchesSet = mutable.BitSet.empty ++ matches
  println(matches.mkString(" "))
  println(next.mkString(" "))
  if (!ys.forall(matchesSet)) println(0)
  */

  val d = p.length - next(p.length)
  //println(d)

  var ok = true
  if (ys.nonEmpty) {
    var prev = ys.head
    for (y <- ys.tail) {
      if ((y - prev) % d != 0) ok = false
      prev = y
    }
  }

  if (!ok) println(0)
  else {
    val occupied = mutable.BitSet.empty
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length - 1
      while (i <= r) {
        occupied += i
        i += 1
      }
      pos = r
    }
    val free = n - occupied.size
    val res = if (free < 0) 0 else BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

import scala.collection._
import scala.collection.mutable.ArrayBuilder

object B 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)
  val p = readLine
  val ys = readInts(_m).map(_ - 1)

  val next = Array.fill(2 * p.length + 2)(0)
  var k = 0
  for (j <- 1 until 2 * p.length) {
    while (k > 0 && (j < p.length && p(k) != p(j))) k = next(k)
    if (j >= p.length || p(k) == p(j)) k += 1
    next(j + 1) = k
  }

  var j = 0
  val matchesBuilder = new ArrayBuilder.ofInt
  for (i <- p.indices) {
    while (j > 0 && p(j) != p(i)) j = next(j)
    if (p(j) == p(i)) j += 1
    if (j == p.length - i) {
      matchesBuilder += i - j + 1//p.length//matches += 1 // match at i - m
      j = next(j)
    }
  }

  val matches = matchesBuilder.result
  val matchesSet = mutable.BitSet.empty ++ matches

  if (!ys.forall(matchesSet)) println(0)
  else {
    val occupied = mutable.BitSet.empty
    var pos = 0
    for (y <- ys) {
      var i = y max pos
      val r = y + p.length - 1
      while (i <= r) {
        occupied += i
        i += 1
      }
      pos = r
    }
    val free = n - occupied.size
    val res = BigInt(26).modPow(free, 1000000007L)
    println(res)
  }
}

object D{
  def main(args: Array[String]){
//   import scala.collection.mutable.PriorityQueue
//    import scala.collection.mutable.ArrayBuffer
    import scala.collection.mutable.TreeSet
    import util.control.Breaks._
    import java.io.{PrintWriter}
    import java.util.{Locale, Scanner}

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

    def nextInt = in.nextInt
    def nextLong = in.nextLong
    def nextDouble = in.nextDouble
    def nextString = in.next
    val n=in.nextInt
    val m=in.nextInt
    val sub=in.next
    val y=(for(i<- 0 until m) yield in.nextInt).toArray
    // index
    val A=new TreeSet[Int]()
    for(k<- 1 to sub.length-1){
      for(l <- A){
        if(sub(k)!=sub(k-l)){
          A-=l
        }
      }
      if(sub(k)==sub(0)){
        A+=k
      }
    }
    var sum=y(0)-1
    var bad=false
    for(i<-1 until m){
      if(y(i)-y(i-1)>=sub.length){
        sum+=y(i)-y(i-1)-sub.length
      }
      else if(!A(y(i)-y(i-1))){
        bad=true
      }
    }
    if(bad){
      out.println(0)
    }
    else{
      if(n-y(m-1)+1>=sub.length){
        sum+=n-y(m-1)-sub.length+1
        var r=1
        for(i<-0 until sum){
          r=(r*26)%1000000007
        }
        out.println(r)
      }
      else{
        out.println(0)
      }
    }
    out.flush
out.close
  }
}


Основой любой социальной сети является отношение дружбы между двумя пользователями в том или ином смысле. В одной известной социальной сети дружба симметрична, то есть если a является другом b, то b также является другом a. В этой же сети есть функция, которая демонстрирует множество людей, имеющих высокую вероятность быть знакомыми для пользователя. Эта функция работает следующим образом. Зафиксируем пользователя x. Пусть некоторый другой человек y, не являющийся другом x на текущий момент, является другом не менее, чем для k% друзей x. Тогда он является предполагаемым другом для x.У каждого человека в социальной сети есть свой уникальный идентификатор — это целое число от 1 до 109. Вам дан список пар пользователей, являющихся друзьями. Определите для каждого упомянутого пользователя множество его предполагаемых друзей.

В первой строке следуют два целых числа m и k (1 ≤ m ≤ 100, 0 ≤ k ≤ 100) — количество пар друзей и необходимый процент общих друзей для того, чтобы считаться предполагаемым другом. В последующих m строках записано по два числа ai, bi (1 ≤ ai, bi ≤ 109, ai ≠ bi), обозначающих идентификаторы пользователей, являющихся друзьями.  Гарантируется, что каждая пара людей фигурирует в списке не более одного раза.

Для всех упомянутых людей в порядке возрастания id выведите информацию о предполагаемых друзьях. Информация должна иметь вид "id:  k id1 id2 ... idk", где id — это id самого человека, k — количество его предполагаемых друзей, а id1, id2, ..., idk — идентификаторы его предполагаемых друзей в возрастающем порядке.

import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet
import scala.collection.mutable.ListBuffer
import scala.io.StdIn

object Main extends App {
  val m :: k :: List() = StdIn.readLine().split(" ").map(_.toInt).toList
  val lines = (1 to m).map(x => StdIn.readLine())

  val pairs = TreeSet(lines.flatMap(_.split(" ").map(_.toInt).toList match {
    case a :: b :: List() => List((a, b), (b, a))
  }).toList: _*)

  val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)

  for (me <- friends.keySet) {
    print(s"$me: ")
    val result = ListBuffer[Int]()
    val myFriends = friends(me)

    for (person <- friends.keySet) {
      var s = 0
      if (person != me && !pairs.contains(person -> me)) {
        for (friend <- myFriends) {
          if (pairs.contains(friend -> person)) {
            s += 1
          }
        }

        if (s * 100 >= k * myFriends.size) {
          result += person
        }
      }
    }

    print(s"${result.size} ")
    println(result.mkString(" "))
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet

object Main extends App with IOUtils {
  val (m, k) = nextIntPair
  val pairsList = (1 to m).map { _ => nextIntPair }

  val pairs = TreeSet(pairsList.flatMap(p => List(p, p.swap)) :_*)

  val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)
  val people = friends.keySet.toList

  def isSuggested(person: Int, me: Int): Boolean = {
    val myFriends = friends(me)
    person != me &&
      !myFriends.contains(person) &&
      (friends(person) & myFriends).size * 100 >= k * myFriends.size
  }

  def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))

  val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)

  result.foreach { case (me, suggested) =>
    println(s"$me: ${suggested.size} ${suggested.mkString(" ")}")
  }
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt
  def nextLong: Long = nextToken.toLong
  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

import scala.collection.immutable.HashSet
import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet

object Main extends App with IOUtils {
  val (m, k) = nextIntPair

  def pairsList = (1 to m).map { _ => nextIntPair}

  val pairs = TreeSet(pairsList.flatMap(p => List(p, p.swap)): _*)

  val friends = TreeMap(pairs.groupBy(_._1).mapValues(_.map(_._2)).toSeq: _*)
  val people = friends.keySet.toList

  def isSuggested(person: Int, me: Int): Boolean = {
    val myFriends = friends(me)
    person != me &&
      !myFriends.contains(person) &&
      (friends(person) & myFriends).size * 100 >= k * myFriends.size
  }

  def suggestedFriends(me: Int): List[Int] = people.filter(isSuggested(_, me))

  val result = people zip (people map suggestedFriends)

  result.foreach { case (me, suggested) =>
    println(s"$me: ${suggested.size} ${suggested.mkString(" ")}")
  }
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import scala.collection.SortedSet
import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet
import scala.io.StdIn

object Main extends App {
  val m :: k :: List() = StdIn.readLine().split(" ").map(_.toInt).toList

  val pairs = TreeSet((1 to m).flatMap(x => StdIn.readLine().split(" ").map(_.toInt).toList match {
    case a :: b :: List() => List((a, b), (b, a))
  }).toList: _*)

  val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)
  val people = friends.keySet.toList

  def isSuggested(person: Int, me: Int): Boolean = {
    val myFriends = friends(me)
    person != me &&
      !myFriends.contains(person) &&
      (friends(person) & myFriends).size * 100 >= k * myFriends.size
  }

  def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))

  val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)

  result.foreach { case (me, suggested) =>
    println(s"$me: ${suggested.size} ${suggested.mkString(" ")}")
  }
}

import java.io.InputStreamReader
import java.io.BufferedReader

import java.util.StringTokenizer

import scala.collection.immutable.TreeMap
import scala.collection.mutable.HashSet
import scala.collection.mutable.ListBuffer

object Main extends App {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }

  val m: Int = nextInt
  val k: Int = nextInt
  var friends = TreeMap[Int, List[Int]]()
  val pairs = new HashSet[(Int, Int)]

  for (i <- 1 to m) {
    val a: Int = nextInt
    val b: Int = nextInt
    if (!friends.contains(a)) {
      friends += a -> List[Int]()
    }

    friends += a -> (b :: friends(a))

    if (!friends.contains(b)) {
      friends += b -> List[Int]()
    }

    friends += b -> (a :: friends(b))

    pairs += a -> b
    pairs += b -> a
  }

  for (me <- friends.keySet) {
    print(s"$me: ")
    val result = ListBuffer[Int]()
    val myFriends = friends(me)

    for (person <- friends.keySet) {
      var s = 0
      if (person != me && !pairs.contains(person -> me)) {
        for (friend <- myFriends) {
          if (pairs.contains(friend -> person)) {
            s += 1
          }
        }

        if (s * 100 >= k * myFriends.size) {
          result += person
        }
      }
    }

    print(s"${result.size} ")
    println(result.mkString(" "))
  }
}

import scala.collection.SortedSet
import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet
import scala.io.StdIn

object Main extends App {
  def intPair(s: String): (Int, Int) = {
    val (s1, s2) = s.span(_ != ' ')
    (s1.toInt, s2.trim().toInt)
  }

  val m :: k :: List() = StdIn.readLine().split(" ").map(_.toInt).toList

  val input = (1 to m).map { _ => StdIn.readLine() }
  val pairs = TreeSet(input.map(intPair).flatMap(p => List(p, p.swap)) :_*)

  val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)
  val people = friends.keySet.toList

  def isSuggested(person: Int, me: Int): Boolean = {
    val myFriends = friends(me)
    person != me &&
      !myFriends.contains(person) &&
      (friends(person) & myFriends).size * 100 >= k * myFriends.size
  }

  def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))

  val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)

  result.foreach { case (me, suggested) =>
    println(s"$me: ${suggested.size} ${suggested.mkString(" ")}")
  }
}

import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.StringTokenizer

import scala.collection.immutable.HashSet
import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet

object Main extends App with IOUtils {
  val (m, k) = nextIntPair

  def pairsList = (1 to m).map { _ => nextIntPair}

  val pairs = TreeSet(pairsList.flatMap(p => List(p, p.swap)): _*)

  val friends = pairs.foldLeft(TreeMap[Int, Set[Int]]()) { (m, p) =>
    m + (p._1 -> (m.getOrElse(p._1, Set()) + p._2))
  }

//  val friends = TreeMap(pairs.groupBy(_._1).mapValues(_.map(_._2)).toSeq: _*)
  val people = friends.keySet.toList

  def isSuggested(person: Int, me: Int): Boolean = {
    val myFriends = friends(me)
    person != me &&
      !myFriends.contains(person) &&
      (friends(person) & myFriends).size * 100 >= k * myFriends.size
  }

  def suggestedFriends(me: Int): List[Int] = people.filter(isSuggested(_, me))

  val result = TreeMap((people zip people.map(suggestedFriends)).toSeq: _*)

  result.foreach { case (me, suggested) =>
    println(s"$me: ${suggested.size} ${suggested.mkString(" ")}")
  }
}

trait IOUtils {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextIntPair: (Int, Int) = (nextInt, nextInt)

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }
}

import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet
import scala.collection.mutable.ListBuffer
import scala.io.Source
import scala.io.StdIn

object Main extends App {
  val m :: k :: List() = StdIn.readLine().split(" ").map(_.toInt).toList

  val pairs = TreeSet(Source.stdin.getLines().flatMap(_.split(" ").map(_.toInt).toList match {
    case a :: b :: List() => List((a, b), (b, a))
  }).toList :_*)

  val friends = TreeMap(pairs.groupBy{ case (a, b) => a }.mapValues(_.map { case (a, b) => b }).toSeq :_*)

  for (me <- friends.keySet) {
    print(s"$me: ")
    val result = ListBuffer[Int]()
    val myFriends = friends(me)

    for (person <- friends.keySet) {
      var s = 0
      if (person != me && !pairs.contains(person -> me)) {
        for (friend <- myFriends) {
          if (pairs.contains(friend -> person)) {
            s += 1
          }
        }

        if (s * 100 >= k * myFriends.size) {
          result += person
        }
      }
    }

    print(s"${result.size} ")
    println(result.mkString(" "))
  }
}

import scala.collection.SortedSet
import scala.collection.immutable.TreeMap
import scala.collection.immutable.TreeSet
import scala.io.StdIn

object Main extends App {
  val m :: k :: List() = StdIn.readLine().split(" ").map(_.toInt).toList

  val pairs = TreeSet((1 to m).flatMap(x => StdIn.readLine().split(" ").map(_.toInt).toList match {
    case a :: b :: List() => List((a, b), (b, a))
  }).toList: _*)

  val friends = TreeMap(pairs.groupBy { case (a, b) => a}.mapValues(_.map { case (a, b) => b}).toSeq: _*)
  val people = friends.keySet.toList

  def isSuggested(person: Int, me: Int): Boolean = {
    val myFriends = friends(me)
    person != me && ((friends(person) & myFriends).size * 100 >= k * myFriends.size)
  }

  def suggestedFriends(me: Int) : List[Int] = people.filter(isSuggested(_, me))

  val result = TreeMap((people zip people.map(suggestedFriends)).toSeq :_*)

  result.foreach { case (me, suggested) =>
    println(s"$me: ${suggested.size} ${suggested.mkString(" ")}")
  }
}

import java.io.InputStreamReader
import java.io.BufferedReader

import java.util.StringTokenizer

import scala.collection.immutable.TreeMap
import scala.collection.mutable.HashSet
import scala.collection.mutable.ListBuffer

object Main extends App {
  var in: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
  var tok: StringTokenizer = null

  def nextInt: Int = nextToken.toInt

  def nextLong: Long = nextToken.toLong

  def nextToken: String = {
    if (tok == null || !tok.hasMoreTokens) {
      tok = new StringTokenizer(in.readLine)
    }

    tok.nextToken
  }

  val m: Int = nextInt
  val k: Int = nextInt
  var friends = TreeMap[Int, List[Int]]()
  val pairs = new HashSet[(Int, Int)]

  for (i <- 1 to m) {
    val a: Int = nextInt
    val b: Int = nextInt
    if (!friends.contains(a)) {
      friends += a -> List[Int]()
    }

    friends += a -> (b :: friends(a))

    if (!friends.contains(b)) {
      friends += b -> List[Int]()
    }

    friends += b -> (a :: friends(b))

    pairs += a -> b
    pairs += b -> a
  }

  for (me <- friends.keySet) {
    print(s"$me: ")
    val result = ListBuffer[Int]()
    val myFriends = friends(me)

    for (person <- friends.keySet) {
      var s = 0
      if (person != me && !pairs.contains(person -> me)) {
        for (friend <- myFriends) {
          if (pairs.contains(friend -> person)) {
            s += 1
          }
        }
      }

      if (s * 100 >= k * myFriends.size) {
        result += person
      }
    }

    print(s"${result.size} ")
    println(result.mkString(" "))
  }
}


Little Petya very much likes gifts. Recently he has received a new laptop as a New Year gift from his mother. He immediately decided to give it to somebody else as what can be more pleasant than giving somebody gifts. And on this occasion he organized a New Year party at his place and invited n his friends there.If there's one thing Petya likes more that receiving gifts, that's watching others giving gifts to somebody else. Thus, he safely hid the laptop until the next New Year and made up his mind to watch his friends exchanging gifts while he does not participate in the process. He numbered all his friends with integers from 1 to n. Petya remembered that a friend number i gave a gift to a friend number pi. He also remembered that each of his friends received exactly one gift.Now Petya wants to know for each friend i the number of a friend who has given him a gift.

The first line contains one integer n (1 ≤ n ≤ 100) — the quantity of friends Petya invited to the party. The second line contains n space-separated integers: the i-th number is pi — the number of a friend who gave a gift to friend number i. It is guaranteed that each friend received exactly one gift. It is possible that some friends do not share Petya's ideas of giving gifts to somebody else. Those friends gave the gifts to themselves.

Print n space-separated integers: the i-th number should equal the number of the friend who gave a gift to friend number i.

object One36A extends App {
	import java.io.PrintWriter
	import java.util.Scanner

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

	import in._
	import out._

	val n = nextInt
	val arr = new Array[Int](n)

	(0 until n).foreach { i =>
		val no = nextInt
		arr(no-1) = i+1
	}
	println(arr.mkString(" "))

	in.close
	out.close
}

object Main extends App {
  def iterate(pointer: Int): Unit = {
    if (pointer == numberOfFriends) return
    else giftedByIdArray(giftMapArray(pointer) - 1) = pointer + 1; iterate(pointer + 1)
  }

  val numberOfFriends = readLine.toInt
  val giftMapArray = readLine.split(" ").map(_.toInt)
  val giftedByIdArray = new Array[Int](numberOfFriends)
  iterate(0)

  println(giftedByIdArray.mkString(" "))
}

import java.util.Scanner

object MainA extends App {
  val sc = new Scanner(System.in)

  val N = sc.nextInt
  val l = for(t <- 0 until N) yield sc.nextInt
  val res = for(i <- 1 to N) yield l.indexOf(i) + 1
  println(res.mkString(" "))
}

object Solution136A extends App {

  def solution() {
    val n = _int
    1.to(n).map(_ => _int).zip(1.to(n)).sortBy(_._1).foreach(p => print(p._2 + " "))
  }

  //////////////////////////////////////////////////
  import java.util.Scanner
  val SC: Scanner = new Scanner(System.in)
  def _line: String = SC.nextLine
  def _int: Int = SC.nextInt
  def _long: Long = SC.nextLong
  def _string: String = SC.next
  solution()
}

import scala.collection.mutable._
import scala.math._
import scala.util._
import scala.util.control.Breaks.break
import scala.util.control.Breaks.breakable
import java.util._
object Main extends App {
  val sc = new Scanner(System.in)
  val n = sc.nextInt
  val t = for(i <- 1 to n) yield sc.nextInt
  val s = for(i <- 1 to n) yield t.indexOf(i) + 1
  println(s.mkString(" "))
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  in.next()
  val data = in.next().split(" ").map(_.toInt)
  var answer = Array.ofDim[Int](data.length)
  data.zipWithIndex.foreach {
    case(index, value) => answer(index - 1) = value + 1
  }
  println(answer.mkString(" "))
}

object Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val n = std.readLine().toInt
    val values = std.readLine().split(" ").map(_.toInt)
    val result = new Array[Int](values.length)
    for (i <- 0 until n) {
      result(values(i)-1) = i + 1
    }
    println(result.mkString(" "))
  }
}

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

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

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

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

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val input = readInts(n).zipWithIndex.toMap.mapValues(_+1)
    val res = (1 to n).foldLeft(List.empty[Int]) {case (arr, i) => arr ++ List(input(i))}
    println(res.mkString(" "))
  }
}

import java.util.Scanner
import java.io.PrintWriter
import scala.annotation.tailrec
import scala.collection.mutable
import scala.util.Random

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

  val N = sc.nextInt
  val presenters = new Array[Int](N)

  for (i <- 1 to N)
    presenters(sc.nextInt - 1) = i

  out.println(presenters.mkString(" "))
  out.close
}

object Presents {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt;
		var function = new Array[Int](n);
		for (i <- 1 to n) {
			val value = scanner.nextInt;
					function(value-1) = i
		}
		for (i <- 1 to n) {
		  print(function(i-1) + " ")
		}
	}
}

import java.io._
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)

  val n = readInt
  def ans = readInts.zip(1 to n).sortBy(_._1).map(_._2).mkString(" ")

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

object Main {
  def main(args: Array[String]) {
    val i = readInt()
    val a = readLine.split(" ").map(_.toInt)
    val r = new Array[Int](a.size)
    for(i <- 0 until a.size) { r(a(i) - 1) = i + 1 }
    println(r.mkString(" "))
  }
}

// Codeforces 136A

object _136A extends App {
  val scanner = new java.util.Scanner(System.in)
  val n = scanner.nextInt
  val presents = Array.fill(n)(scanner.nextInt)
  val answer = Array.tabulate(n)(i => presents.indexOf(i+1)+1)
  println(answer.mkString(" "))
}

import Array._
import scala.io.StdIn.readLine
object problem {
  def main(args: Array[String]) {
  val n = readLine.toInt
    val s = new Array[Int](n + 1)
    val A = readLine.split(" ").map(_.toInt)
    for(i <- 0 until n){
      s(A(i)) = i + 1
    }
    for(i <- 1 to n) print(s(i) + " ")
  }
}

import java.util.Scanner

object HelloWorldMain {

  def main(args: Array[String]): Unit = {
    val sc = new Scanner(System.in)

    val n = sc.nextInt()

    var array = new Array[Int](n)

    for( i  <- 1 to n ){
      array(sc.nextInt()-1) = i

    }

    array.foreach(c => print(c  + " "))
  }
}

import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Presents {
  def main(args: Array[String]) {
     val n = readInt
     println((0 +: readLine.split(' ').map(_.toInt)).
         zipWithIndex.sortBy(_._1).tail.map(_._2).mkString(" "))
  }

}

import scala.util.Sorting
import scala.io.StdIn

object App {

  def main(args: Array[String]) {

    val n = StdIn.readLine().toInt

    val B = StdIn.readLine().split(" ").map(_.toInt)
    val A:Array[Int] = new Array[Int](n)
    for(i <- 0 to n - 1) {
      A(B(i) - 1) = i + 1;
    }

    println(A.mkString(" "))

  }

}

import java.util.Scanner

object TEST extends App {
    val n =readInt()
    val a : List[Int] = readLine.split(' ').toList.map(_.toInt)
    val ans = (for(i <- 1 to n) yield a.indexOf(i)+1).mkString(" ")
    print(ans)
}

import scala.io.StdIn._

object Task extends App{
  val n = readInt
  val ps = readLine.split(" ").map(_.toInt)

  val ans = ps.zipWithIndex.sortBy(_._1).map(_._2 + 1)

  println(ans.mkString(" "))
}


Miyako came to the flea kingdom with a ukulele. She became good friends with local flea residents and played beautiful music for them every day.In return, the fleas made a bigger ukulele for her: it has $$$n$$$ strings, and each string has $$$(10^{18} + 1)$$$ frets numerated from $$$0$$$ to $$$10^{18}$$$. The fleas use the array $$$s_1, s_2, \ldots, s_n$$$ to describe the ukulele's tuning, that is, the pitch of the $$$j$$$-th fret on the $$$i$$$-th string is the integer $$$s_i + j$$$.Miyako is about to leave the kingdom, but the fleas hope that Miyako will answer some last questions for them.Each question is in the form of: "How many different pitches are there, if we consider frets between $$$l$$$ and $$$r$$$ (inclusive) on all strings?"Miyako is about to visit the cricket kingdom and has no time to answer all the questions. Please help her with this task!Formally, you are given a matrix with $$$n$$$ rows and $$$(10^{18}+1)$$$ columns, where the cell in the $$$i$$$-th row and $$$j$$$-th column ($$$0 \le j \le 10^{18}$$$) contains the integer $$$s_i + j$$$. You are to answer $$$q$$$ queries, in the $$$k$$$-th query you have to answer the number of distinct integers in the matrix from the $$$l_k$$$-th to the $$$r_k$$$-th columns, inclusive.

The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 100\,000$$$) — the number of strings. The second line contains $$$n$$$ integers $$$s_1, s_2, \ldots, s_n$$$ ($$$0 \leq s_i \leq 10^{18}$$$) — the tuning of the ukulele. The third line contains an integer $$$q$$$ ($$$1 \leq q \leq 100\,000$$$) — the number of questions. The $$$k$$$-th among the following $$$q$$$ lines contains two integers $$$l_k$$$，$$$r_k$$$ ($$$0 \leq l_k \leq r_k \leq 10^{18}$$$) — a question from the fleas.

Output one number for each question, separated by spaces — the number of different pitches.

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 java.util.Arrays

  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 = nal(N)
    sort(S)
    debug("S")
    debug(S)
    val D = Array.ofDim[Long](N - 1)
    REP(N - 1) { i =>
      D(i) = max(0, S(i + 1) - S(i) - 1)
    }
    sort(D)
    val cum = cumSum(D)
    debug("D")
    debug(D)
    debug(cum)

    val distinct = S.distinct.length

    val ans = ArrayBuffer[Long]()
    REP(ni()) { _ =>
      val l, r = nl()
      val d = r - l
      val cntL = lowerBound(D, d)
      debug(s"cntL:$cntL")
      ans += cum(cntL) + (r - l) * (N - cntL) + distinct
    }

    out.println(ans.mkString(" "))
  }

  def sort(a: Array[Long]): Array[Long] = {
    val n = a.length
    REP(n) { i =>
      val j = scala.util.Random.nextInt(n - i) + i
      val tmp = a(i)
      a(i) = a(j)
      a(j) = tmp
    }
    Sorting.stableSort(a)
    a
  }

  def lowerBound(a: Array[Long], x: Long): Int = {
    def step(l: Int, h: Int): Int = {
      if (h - l == 1) h
      else {
        val mid = (l + h) / 2
        if (a(mid) >= x) step(l, mid)
        else step(mid, h)
      }
    }

    step(-1, a.length)
  }

  private val oj = System.getenv("ATCODER_DEBUG") == null

  def DEBUG(f: => Unit): Unit = {
    if (!oj){ f }
  }

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

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

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

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

  def debugL(num: => Long): Unit = DEBUG {
    System.err.println(num)
  }

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

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

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

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

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

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


You are given an array $$$a$$$ consisting of $$$n$$$ integers. You can perform the following operations with it:   Choose some positions $$$i$$$ and $$$j$$$ ($$$1 \le i, j \le n, i \ne j$$$), write the value of $$$a_i \cdot a_j$$$ into the $$$j$$$-th cell and remove the number from the $$$i$$$-th cell;  Choose some position $$$i$$$ and remove the number from the $$$i$$$-th cell (this operation can be performed no more than once and at any point of time, not necessarily in the beginning). The number of elements decreases by one after each operation. However, the indexing of positions stays the same. Deleted numbers can't be used in the later operations.Your task is to perform exactly $$$n - 1$$$ operations with the array in such a way that the only number that remains in the array is maximum possible. This number can be rather large, so instead of printing it you need to print any sequence of operations which leads to this maximum number. Read the output format to understand what exactly you need to print.

The first line contains a single integer $$$n$$$ ($$$2 \le n \le 2 \cdot 10^5$$$) — the number of elements in the array. The second line contains $$$n$$$ integers $$$a_1, a_2, \dots, a_n$$$ ($$$-10^9 \le a_i \le 10^9$$$) — the elements of the array.

Print $$$n - 1$$$ lines. The $$$k$$$-th line should contain one of the two possible operations. The operation of the first type should look like this: $$$1~ i_k~ j_k$$$, where $$$1$$$ is the type of operation, $$$i_k$$$ and $$$j_k$$$ are the positions of the chosen elements. The operation of the second type should look like this: $$$2~ i_k$$$, where $$$2$$$ is the type of operation, $$$i_k$$$ is the position of the chosen element. Note that there should be no more than one such operation. If there are multiple possible sequences of operations leading to the maximum number — print any of them.

NoteLet X be the removed number in the array. Let's take a look at all the examples:The first example has, for example, the following sequence of transformations of the array: $$$[5, -2, 0, 1, -3] \to [5, -2, X, 1, -3] \to [X, -10, X, 1, -3] \to$$$ $$$[X, X, X, -10, -3] \to [X, X, X, X, 30]$$$. Thus, the maximum answer is $$$30$$$. Note, that other sequences that lead to the answer $$$30$$$ are also correct.The second example has, for example, the following sequence of transformations of the array: $$$[5, 2, 0, 4, 0] \to [5, 2, X, 4, 0] \to [5, 2, X, 4, X] \to [X, 10, X, 4, X] \to$$$ $$$[X, X, X, 40, X]$$$. The following answer is also allowed: 1 5 31 4 21 2 12 3Then the sequence of transformations of the array will look like this: $$$[5, 2, 0, 4, 0] \to [5, 2, 0, 4, X] \to [5, 8, 0, X, X] \to [40, X, 0, X, X] \to$$$ $$$[40, X, X, X, X]$$$.The third example can have the following sequence of transformations of the array: $$$[2, -1] \to [2, X]$$$.The fourth example can have the following sequence of transformations of the array: $$$[0, -10, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.The fifth example can have the following sequence of transformations of the array: $$$[0, 0, 0, 0] \to [X, 0, 0, 0] \to [X, X, 0, 0] \to [X, X, X, 0]$$$.

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 A = na(N)

    val cntNeg = A count(_ < 0)
    val cntZero = A count(_ == 0)

    val mulVs = ArrayBuffer[Int]()
    val mulDels = ArrayBuffer[Int]()

    if (cntZero == N || cntNeg == 1 && cntZero == N - 1) {
      rep(N, 1) { i =>
        mulVs += i
      }
    } else if (cntNeg == 1 && cntZero == N - 1) {
//      val neg = A indexWhere (_ < 0)
//      rep(N - 1, 1) { i =>
//        if (i != neg) mulVs += (i , i + 1)
//        else mulDels += i + 1
//      }
    } else {

      val delNeg = if (cntNeg % 2 == 0) -1
      else {
        var mxNeg = Integer.MIN_VALUE
        rep(N) { i =>
          if (A(i) < 0) mxNeg = max(mxNeg, A(i))
        }
        A.indexWhere(_ == mxNeg)
      }
      rep(N) { i =>
        if (i == delNeg || A(i) == 0) mulDels += i + 1
        else mulVs += i + 1
      }
    }

    val dels = ArrayBuffer[Int]()
    val muls = ArrayBuffer[(Int, Int)]()
    rep(mulVs.length - 1) { i =>
      muls += ((mulVs(i), mulVs(i + 1)))
    }

    if (mulDels.nonEmpty) {
      rep(mulDels.length - 1) { i =>
        muls += ((mulDels(i), mulDels(i + 1)))
      }
      dels += mulDels.last
    }

    muls foreach { case (i, j) =>
      out.println(s"1 $i $j")
    }

    dels foreach { i =>
      out.println(s"2 $i")
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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 A = na(N)

    val cntNeg = A count(_ < 0)
    val cntZero = A count(_ == 0)

    val dels = ArrayBuffer[Int]()
    val muls = ArrayBuffer[(Int, Int)]()
    if (cntZero == N) {
      rep(N - 1, 1) { i =>
        dels += i + 1
      }
    } else if (cntNeg == 1 && cntZero == N - 1) {
      val last = A.indexWhere(_ == 0)
      rep(N) { i =>
        if (i != last) dels += i + 1
      }
    } else {
      val delNeg = if (cntNeg % 2 == 0) -1
      else {
        var mxNeg = Integer.MIN_VALUE
        rep(N) { i =>
          if (A(i) < 0) mxNeg = max(mxNeg, A(i))
        }
        A.indexWhere(_ == mxNeg)
      }
      val mulVs = ArrayBuffer[Int]()
      rep(N) { i =>
        if (i == delNeg || A(i) == 0) dels += i + 1
        else mulVs += i + 1
      }
      rep(mulVs.length - 1) { i =>
        muls += ((mulVs(i), mulVs(i + 1)))
      }
    }

    dels foreach { i =>
      out.println(s"2 $i")
    }

    muls foreach { case (i, j) =>
      out.println(s"1 $i $j")
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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

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 A = na(N)

    val cntNeg = A count(_ < 0)
    val cntZero = A count(_ == 0)

    val dels = ArrayBuffer[Int]()
    val muls = ArrayBuffer[(Int, Int)]()
    if (cntZero == N) {
      rep(N - 1, 1) { i =>
        dels += i + 1
      }
    } else if (cntNeg == 1 && cntZero == N - 1) {
      val last = A.indexWhere(_ == 0)
      rep(N) { i =>
        if (i != last) dels += i + 1
      }
    } else {
      val delNeg = if (cntNeg % 2 == 1) A.indexWhere(_ < 0) else -1
      val mulVs = ArrayBuffer[Int]()
      rep(N) { i =>
        if (i == delNeg || A(i) == 0) dels += i + 1
        else mulVs += i + 1
      }
      rep(mulVs.length - 1) { i =>
        muls += ((mulVs(i), mulVs(i + 1)))
      }
    }

    dels foreach { i =>
      out.println(s"2 $i")
    }

    muls foreach { case (i, j) =>
      out.println(s"1 $i $j")
    }
  }

  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): Array[Int] = map(n)(_ => ni())
  def nal(n: Int): Array[Long] = map(n)(_ => nl())
  def nm(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)(f: Int => A): Array[A] = {
    val res = Array.ofDim[A](n)
    rep(n)(i => res(i) = f(i))
    res
  }

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


You are given two segments $$$[l_1; r_1]$$$ and $$$[l_2; r_2]$$$ on the $$$x$$$-axis. It is guaranteed that $$$l_1 < r_1$$$ and $$$l_2 < r_2$$$. Segments may intersect, overlap or even coincide with each other.    The example of two segments on the $$$x$$$-axis. Your problem is to find two integers $$$a$$$ and $$$b$$$ such that $$$l_1 \le a \le r_1$$$, $$$l_2 \le b \le r_2$$$ and $$$a \ne b$$$. In other words, you have to choose two distinct integer points in such a way that the first point belongs to the segment $$$[l_1; r_1]$$$ and the second one belongs to the segment $$$[l_2; r_2]$$$.It is guaranteed that the answer exists. If there are multiple answers, you can print any of them.You have to answer $$$q$$$ independent queries.

The first line of the input contains one integer $$$q$$$ ($$$1 \le q \le 500$$$) — the number of queries. Each of the next $$$q$$$ lines contains four integers $$$l_{1_i}, r_{1_i}, l_{2_i}$$$ and $$$r_{2_i}$$$ ($$$1 \le l_{1_i}, r_{1_i}, l_{2_i}, r_{2_i} \le 10^9, l_{1_i} < r_{1_i}, l_{2_i} < r_{2_i}$$$) — the ends of the segments in the $$$i$$$-th query.

Print $$$2q$$$ integers. For the $$$i$$$-th query print two integers $$$a_i$$$ and $$$b_i$$$ — such numbers that $$$l_{1_i} \le a_i \le r_{1_i}$$$, $$$l_{2_i} \le b_i \le r_{2_i}$$$ and $$$a_i \ne b_i$$$. Queries are numbered in order of the input. It is guaranteed that the answer exists. If there are multiple answers, you can print any.

//package codeforces.contest1108

object TwoDistinctPoints {
  def main(args: Array[String]): Unit = {
    val q = io.StdIn.readInt()
    (1 to q).foreach { _ =>
      val Array(l1, r1, l2, r2) = io.StdIn.readLine.split(" ").map(_.toInt)

      val result: List[(Int, Int)] = for {
        a <- List(l1, r1)
        b <- List(l2, r2)
        if a != b
      } yield (a, b)

      println(result.head._1 + " " + result.head._2)
    }
  }

}

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

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

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

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

  def solve(): Unit = {
    REP(ni()) { _ =>
      val l1, r1, l2, r2 = ni()
      if (l1 == r2) {
        out.println(s"$r1 $l1")
      } else {
        out.println(s"$l1 $r2")
      }
    }
  }

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

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

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

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

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

import scala.io.StdIn

object A1108 {
  def main(args: Array[String]): Unit = {
    val n = StdIn.readInt()
    for {i <- 1 to n} {
      val Array(l1, r1, l2, r2) = StdIn.readLine().split(' ').map(_.toInt)
      println(l1 + " " + (if (l1 == l2) r2 else l2))
    }
  }
}

object TwoDistinctPoints extends App {

  val q = io.StdIn.readLine().toInt

  for (_ <- 1 to q) {

    val line = io.StdIn.readLine.split(" ").map(_.toInt)
    val (l1, r1, l2, r2) = (line(0), line(1), line(2), line(3))

    val firstAns  = l1
    val secondAns = if (l2 == firstAns) l2 + 1 else l2

    println(s"$firstAns $secondAns")
  }
}

object Main {

  def main(args: Array[String]) {

    val std = scala.io.StdIn
    val n = std.readLine().toInt

    for (_ <- 0 until n) {
      val values = std.readLine().split(" ").map(_.toInt)
      if (values(0) <= values(2)) {
        println(values(0) + " " + values(3))
      } else {
        println(values(1) + " " + values(2))
      }
    }
  }
}

object CF_535_3_A {
// date: 25/01/2019

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

  def solve(in: In): Out = {
    val (xs) = in
    for {
      Seq(l1,r1,l2,r2) <- xs
    } yield {
      val b = if(l2 != l1) l2
                     else l2 + 1
      (l1, b)
    }
  }

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

  def formatIn(i: Input): In       = i.getLines(i.int).map(_.intSeq)
  def formatOut(out: Out): String  = out.map{case (a,b) => s"$a $b"}.mkString("\n")

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

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

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

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

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

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

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


Monocarp and Bicarp live in Berland, where every bus ticket consists of $$$n$$$ digits ($$$n$$$ is an even number). During the evening walk Monocarp and Bicarp found a ticket where some of the digits have been erased. The number of digits that have been erased is even.Monocarp and Bicarp have decided to play a game with this ticket. Monocarp hates happy tickets, while Bicarp collects them. A ticket is considered happy if the sum of the first $$$\frac{n}{2}$$$ digits of this ticket is equal to the sum of the last $$$\frac{n}{2}$$$ digits.Monocarp and Bicarp take turns (and Monocarp performs the first of them). During each turn, the current player must replace any erased digit with any digit from $$$0$$$ to $$$9$$$. The game ends when there are no erased digits in the ticket.If the ticket is happy after all erased digits are replaced with decimal digits, then Bicarp wins. Otherwise, Monocarp wins. You have to determine who will win if both players play optimally.

The first line contains one even integer $$$n$$$ $$$(2 \le n \le 2 \cdot 10^{5})$$$ — the number of digits in the ticket. The second line contains a string of $$$n$$$ digits and "?" characters — the ticket which Monocarp and Bicarp have found. If the $$$i$$$-th character is "?", then the $$$i$$$-th digit is erased. Note that there may be leading zeroes. The number of "?" characters is even.

If Monocarp wins, print "Monocarp" (without quotes). Otherwise print "Bicarp" (without quotes).

NoteSince there is no question mark in the ticket in the first example, the winner is determined before the game even starts, and it is Bicarp.In the second example, Bicarp also wins. After Monocarp chooses an erased digit and replaces it with a new one, Bicap can choose another position with an erased digit and replace it with the same digit, so the ticket is happy.

object Main extends App {
  import scala.io.StdIn._
  val n = readInt()
  val str = readLine.trim
  val left = str.take(n / 2)
  val right = str.drop(n / 2)
  val leftSum = left.map(c ⇒ if (c.isDigit) c.asDigit else 0).sum
  val rightSum = right.map(c ⇒ if (c.isDigit) c.asDigit else 0).sum
  val leftFree = left.count(_ == '?')
  val rightFree = right.count(_ == '?')
  if (leftSum < rightSum) {
    val diff = rightSum - leftSum
    val freeDiff = (leftFree - rightFree) / 2
    if (freeDiff >= 0 && diff == freeDiff * 9) {
      println("Bicarp")
    }else {
      println("Monocarp")
    }
  }else {
    val diff = leftSum - rightSum
    val freeDiff = (rightFree - leftFree) / 2
    if (freeDiff >= 0 && diff == freeDiff * 9) {
      println("Bicarp")
    }else {
      println("Monocarp")
    }
  }
}


The little girl loves the problems on array queries very much.One day she came across a rather well-known problem: you've got an array of $$$n$$$ elements (the elements of the array are indexed starting from 1); also, there are $$$q$$$ queries, each one is defined by a pair of integers $$$l_i$$$, $$$r_i$$$ $$$(1 \le l_i \le r_i \le n)$$$. You need to find for each query the sum of elements of the array with indexes from $$$l_i$$$ to $$$r_i$$$, inclusive.The little girl found the problem rather boring. She decided to reorder the array elements before replying to the queries in a way that makes the sum of query replies maximum possible. Your task is to find the value of this maximum sum.

The first line contains two space-separated integers $$$n$$$ ($$$1 \le n \le 2\cdot10^5$$$) and $$$q$$$ ($$$1 \le q \le 2\cdot10^5$$$) — the number of elements in the array and the number of queries, correspondingly. The next line contains $$$n$$$ space-separated integers $$$a_i$$$ ($$$1 \le a_i \le 2\cdot10^5$$$) — the array elements. Each of the following $$$q$$$ lines contains two space-separated integers $$$l_i$$$ and $$$r_i$$$ ($$$1 \le l_i \le r_i \le n$$$) — the $$$i$$$-th query.

In a single line print, a single integer — the maximum sum of query replies after the array elements are reordered. Please, do not use the %lld specifier to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specifier.

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(n, q) = StdIn.readLine().split(" ").map(_.toInt)

  val a: List[Int] = StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _).toList

  val d = Array.fill[Int](n+1)(0)

  def lsb(i: Int): Int = i & (-i)

  def update(i: Int, c: Int): Unit = {
    var ii = i

    while (ii <= n) {
      d(ii) += c
      ii += lsb(ii)
    }
  }

  def range_inc(l: Int, r: Int): Unit = {
    update(l, 1)
    update(r+1, -1)
  }

  def query(i: Int): Int = {
    var ii = i
    var sum = 0

    while (ii> 0) {
      sum+=d(ii)
      ii -= lsb(ii)
    }
    sum
  }

  for (i <- 1 to q) {
    val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)

    range_inc(l, r)
  }

  println((1 to n).map(i => query(i)).sortWith(_ > _).zip(a).foldLeft[Long](0)((r: Long, t) => r + t._1.toLong * t._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, q) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt).sorted
  val frequency = Array.ofDim[Int](n)
  (1 to q).foreach { _ =>
    val Array(l, r) = in.next().split(' ').map(_.toInt - 1)
    frequency(l) += 1
    if (r != n - 1)
      frequency(r + 1) -= 1
  }
  val sortedFreq = frequency.foldLeft((List.empty[Long], 0l)) {
    case((list, soFar), i) => (soFar + i :: list, soFar + i)
  }._1.sorted
  println(sortedFreq.zip(data).foldLeft(0l) {
    case(acc, (count, value)) => acc + count * value
  })

}

object Main {
  private def scalaMergeSort(a: Array[Long], lo: Int, hi: Int, scratch: Array[Long]) {
    if (lo < hi) {
      val mid = (lo+hi) / 2
      scalaMergeSort(a, lo, mid, scratch)
      scalaMergeSort(a, mid+1, hi, scratch)
      var k, t_lo = lo
      var t_hi = mid + 1
      while (k <= hi) {
        if ((t_lo <= mid) && ((t_hi > hi) || (a(t_lo) >= a(t_hi)))) {
          scratch(k) = a(t_lo)
          t_lo += 1
        } else {
          scratch(k) = a(t_hi)
          t_hi += 1
        }
        k += 1
      }
      k = lo
      while (k <= hi) {
        a(k) = scratch(k)
        k += 1
      }
    }
  }

  def scalaMergeSortPerform(a: Array[Long]) {
    scalaMergeSort(a, 0, a.length - 1, Array.ofDim[Long](a.length))
  }

  def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {
    var al_next = l
    var am_next = m + 1
    for (i <- l to r)
      if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {
        b(i) = a(al_next)
        al_next += 1
      }
      else {
        b(i) = a(am_next)
        am_next += 1
      }
  }
  def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {
    if (l >= r)
      return
    val m = (l + r) / 2
    mergeSortAct(a, b, l, m)
    mergeSortAct(a, b, m+1, r)
    merge(a, b, l, r, m)
    //Array.copy(b, l, a, l, r - l + 1)
    for (i <- l to r)
      a(i) = b(i)
  }
  def mergeSort(a: Array[Long]) {
    mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)
  }
  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Long](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    scalaMergeSortPerform(array)
    scalaMergeSortPerform(b)
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

import scala.util.Sorting
//import java.util.Arrays
object Main {
  def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {
    var al_next = l
    var am_next = m + 1
    for (i <- l to r)
      if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {
        b(i) = a(al_next)
        al_next += 1
      }
      else {
        b(i) = a(am_next)
        am_next += 1
      }
  }
  def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {
    if (l >= r)
      return
    val m = (l + r) / 2
    mergeSortAct(a, b, l, m)
    mergeSortAct(a, b, m+1, r)
    merge(a, b, l, r, m)
    //Array.copy(b, l, a, l, r - l + 1)
    for (i <- l to r)
      a(i) = b(i)
  }
  def mergeSort(a: Array[Long]) {
    mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)
  }
  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Long](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    /*Arrays.sort(array)
    Arrays.sort(b)*/
    /*Sorting.stableSort(array)
    Sorting.stableSort(b)*/
    mergeSort(array)
    mergeSort(b)
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

//import scala.util.Sorting
//import java.util.Arrays
object Main {

  private def scalaMergeSort(a: Array[Long], lo: Int, hi: Int, scratch: Array[Long], f: (Long,Long) => Boolean) {
    if (lo < hi) {
      val mid = (lo+hi) / 2
      scalaMergeSort(a, lo, mid, scratch, f)
      scalaMergeSort(a, mid+1, hi, scratch, f)
      var k, t_lo = lo
      var t_hi = mid + 1
      while (k <= hi) {
        if ((t_lo <= mid) && ((t_hi > hi) || (a(t_lo) >= a(t_hi)))) {
          scratch(k) = a(t_lo)
          t_lo += 1
        } else {
          scratch(k) = a(t_hi)
          t_hi += 1
        }
        k += 1
      }
      k = lo
      while (k <= hi) {
        a(k) = scratch(k)
        k += 1
      }
    }
  }

  def scalaMergeSortPerform(a: Array[Long]) {
    scalaMergeSort(a, 0, a.length - 1, Array.ofDim[Long](a.length), (a:Long, b:Long) => a < b)
  }

  def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {
    var al_next = l
    var am_next = m + 1
    for (i <- l to r)
      if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {
        b(i) = a(al_next)
        al_next += 1
      }
      else {
        b(i) = a(am_next)
        am_next += 1
      }
  }
  def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {
    if (l >= r)
      return
    val m = (l + r) / 2
    mergeSortAct(a, b, l, m)
    mergeSortAct(a, b, m+1, r)
    merge(a, b, l, r, m)
    //Array.copy(b, l, a, l, r - l + 1)
    for (i <- l to r)
      a(i) = b(i)
  }
  def mergeSort(a: Array[Long]) {
    mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)
  }
  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Long](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    /*Arrays.sort(array)
    Arrays.sort(b)*/
    scalaMergeSortPerform(array)
    scalaMergeSortPerform(b)
    /*mergeSort(array)
    mergeSort(b)*/
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

//import scala.util.Sorting
import java.util.Arrays
object Main {
  def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {
    var al_next = l
    var am_next = m + 1
    for (i <- l to r)
      if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {
        b(i) = a(al_next)
        al_next += 1
      }
      else {
        b(i) = a(am_next)
        am_next += 1
      }
  }
  def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {
    if (l >= r)
      return
    val m = (l + r) / 2
    mergeSortAct(a, b, l, m)
    mergeSortAct(a, b, m+1, r)
    merge(a, b, l, r, m)
    Array.copy(b, l, a, l, r - l + 1)
  }
  def mergeSort(a: Array[Long]) {
    mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)
  }
  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Long](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    Arrays.sort(array)
    Arrays.sort(b)
    /*mergeSort(array)
    mergeSort(b)*/
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

import scala.util.Sorting
object Main {
  def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {
    var al_next = l
    var am_next = m + 1
    for (i <- l to r)
      if (am_next > r || (al_next <= m && a(al_next) < a(am_next))) {
        b(i) = a(al_next)
        al_next += 1
      }
      else {
        b(i) = a(am_next)
        am_next += 1
      }
  }
  def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {
    if (l >= r)
      return
    val m = (l + r) / 2
    mergeSortAct(a, b, l, m)
    mergeSortAct(a, b, m+1, r)
    merge(a, b, l, r, m)
    Array.copy(b, l, a, l, r - l + 1)
  }
  def mergeSort(a: Array[Long]) {
    mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)
  }
  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Long](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    mergeSort(array)
    mergeSort(b)
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

import scala.util.Sorting
object Main {
  def readLineOfNumsL = readLine split ' ' map(_.toLong) toList
  def readLineOfNumsI = readLine split ' ' map(_.toInt) toList
  def main(args: Array[String]) = {
    val List(n, q) = readLineOfNumsI
    val array = readLineOfNumsL
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val List(l, r) = readLineOfNumsI
      d(l-1) += 1
      d(r) -= 1
    }
    val b = d.tail.view.init.scanLeft(d.head) (_ + _)
    println((array.sorted, b.sorted).zipped map (_ * _) sum)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Int](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    println((array.sorted, b.sorted).zipped map (_ * _) sum)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
 //   val b = d.tail.scanLeft(d.head) (_ + _)

    val b = Array.ofDim[Int](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    println((array.sorted, b.sorted).zipped map (_ * _) sum)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = d.tail.view.init.scanLeft(d.head) (_ + _)
    println((array.sorted, b.sorted).zipped map (_ * _) sum)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Int](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    val sortedArray = array.sorted;
    val sortedB = b.sorted;
    var result = 0L
    for (i <- 0 to (n-1))
      result += sortedArray(i) * sortedB(i)
    println(result)
  }
}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(n, q) = StdIn.readLine().split(" ").map(_.toInt)

  val a: List[Int] = StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _).toList

  val d = Array.fill[Int](n+1)(0)

  def lsb(i: Int): Int = i & (-i)

  def update(i: Int, c: Int): Unit = {
    var ii = i

    while (ii <= n) {
      d(ii) += c
      ii += lsb(ii)
    }
  }

  def range_inc(l: Int, r: Int): Unit = {
    update(l, 1)
    update(r+1, -1)
  }

  def query(i: Int): Int = {
    var ii = i
    var sum = 0

    while (ii> 0) {
      sum+=d(ii)
      ii -= lsb(ii)
    }
    sum
  }

  for (i <- 1 to q) {
    val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)

    range_inc(l, r)
  }

  println((1 to n).map(i => query(i)).sortWith(_ > _).zip(a).foldLeft(0)((r, t) => r + t._1 * t._2))

}

import scala.io.StdIn

/**
  * @author traff
  */

object Main extends App {
  val Array(n, q) = StdIn.readLine().split(" ").map(_.toInt)

  val a: List[Int] = StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _).toList

  val d = Array.fill[Int](n+1)(0)

  def lsb(i: Int): Int = i & (-i)

  def update(i: Int, c: Int): Unit = {
    var ii = i

    while (ii <= n) {
      d(ii) += c
      ii += lsb(ii)
    }
  }

  def range_inc(l: Int, r: Int): Unit = {
    update(l, 1)
    update(r+1, -1)
  }

  def query(i: Int): Int = {
    var ii = i
    var sum = 0

    while (ii> 0) {
      sum+=d(ii)
      ii -= lsb(ii)
    }
    sum
  }

  for (i <- 1 to q) {
    val Array(l, r) = StdIn.readLine().split(" ").map(_.toInt)

    range_inc(l, r)
  }

  println((1 to n).map(i => query(i)).sortWith(_ > _).zip(a).foldLeft[Long](0)((r: Long, t) => r + t._1 * t._2))

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val Array(n, q) = in.next().split(' ').map(_.toInt)
  val data = in.next().split(' ').map(_.toInt).sorted
  val frequency = Array.ofDim[Int](n)
  (1 to q).foreach { _ =>
    val Array(l, r) = in.next().split(' ').map(_.toInt - 1)
    frequency(l) += 1
    if (r != n - 1)
      frequency(r + 1) -= 1
  }
  val sortedFreq = frequency.foldLeft((List.empty[Int], 0)) {
    case((list, soFar), i) => (soFar + i :: list, soFar + i)
  }._1.sorted
  println(sortedFreq.zip(data).foldLeft(0l) {
    case(acc, (count, value)) => acc + count * value
  })

}

import scala.util.Sorting
object Main {
  def merge(a: Array[Long], b: Array[Long], l: Int, r:Int, m:Int) {
    var al_next = l
    var am_next = m + 1
    for (i <- l to r)
      if (am_next > r || a(al_next) < a(am_next)) {
        b(i) = a(al_next)
        al_next += 1
      }
      else {
        b(i) = a(am_next)
        am_next += 1
      }
  }
  def mergeSortAct(a: Array[Long], b: Array[Long], l: Int, r: Int) {
    if (l >= r)
      return
    val m = (l + r) / 2
    mergeSortAct(a, b, l, m)
    mergeSortAct(a, b, m+1, r)
    merge(a, b, l, r, m)
    Array.copy(b, l, a, l, r - l + 1)
  }
  def mergeSort(a: Array[Long]) {
    mergeSortAct(a, Array.ofDim[Long](a.length), 0, a.length - 1)
  }
  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Long](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    mergeSort(array)
    mergeSort(b)
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsI()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Int](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    Sorting.quickSort(array)
    Sorting.quickSort(b)
    var result = 0
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = d.scanLeft(0)(_ + _)
    println((array.sorted, b.sorted).zipped map (_ * _) sum)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = Array.ofDim[Int](n)
    var count = 0
    for (i <- 0 to (n-1)) {
      count += d(i)
      b(i) = count
    }
    val sortedArray = array.sorted;
    val sortedB = b.sorted;
    var result = 0L
    for (i <- 0 to (n-1))
      result += array(i) * b(i)
    println(result)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = d.tail.scanLeft(d.head) (_ + _)
    println((array.sorted, b.sorted).zipped map (_ * _) sum)
  }
}

import scala.util.Sorting
object Main {

  def readLineOfNumsL(): Array[Long] = readLine().split(" ").map(_.toLong)
  def readLineOfNumsI(): Array[Int] = readLine().split(" ").map(_.toInt)
  def main(args: Array[String]) = {
    val Array(n, q) = readLineOfNumsI()
    val array = readLineOfNumsL()
    val d = Array.ofDim[Int](n+1)
    for (i <- 1 to q) {
      val Array(l, r) = readLineOfNumsI()
      d(l-1) += 1
      d(r) -= 1
    }
    val b = d.tail.scanLeft(d.head) (_ + _)
    println((array.sorted, b.sorted).zipped.map(_ * _).sum)
  }
}