import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], level : Int = 0) = {
      @tailrec
      def inner (x: List[Char], level : Int, acc : List[Int]) : List[Int] = {
        x match {
          case '(' :: tail => inner(tail, level + 1, level + 1 :: acc)
          case ')' :: tail => inner(tail, level - 1, level - 1 :: acc)
          case _ :: tail => inner(tail, level, level :: acc)
          case Nil => acc.reverse
        }
      }
      inner(x, level, Nil)
    }

    @tailrec def zeroFixer (l : List[Int], acc: Int = 0, accList : List[Int] = Nil) : List[Int] = {
      l match {
        case x :: Nil => (acc + x :: accList).reverse
        case x :: tail => zeroFixer(tail, acc + x - 1, 1 :: accList)
        case Nil => accList.reverse
      }
    }

    @tailrec def stringFiller (hashes: List[Int], str: List[Char], acc : List[Char] = Nil) : List[Char] = {
      str match {
          case '#' :: tail => stringFiller(hashes.tail, tail, (")" * hashes.head).toList ::: acc)
          case x :: tail => stringFiller(hashes, tail, x :: acc)
          case Nil => acc.reverse
      }
    }

    val chars = str.toList
    val charRanks = balanceChecker(chars)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    val hashRankDiffFixed = zeroFixer(hashRankDiffButLast :+ lastItem)
    val strFilledValidation = balanceChecker(stringFiller(hashRankDiffFixed, chars))

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFixed)
    println(strFilledValidation)
    */

    if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

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

object A 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 s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false
  var lastAdd = 0

  val lastHash = s.lastIndexOf('#')
  val hashCnt = s.count(_ == '#')
  val openCnt = s.count(_ == '(')
  val closeCnt = s.count(_ == ')')

  for (i <- s.indices) s(i) match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      lastAdd = if (i == lastHash) math.max(1, openCnt - closeCnt - cntsAdd) else 1
      cntsAdd += lastAdd
      cntClose += lastAdd
      if (cntClose > cntOpen) bad = true
  }

  if (bad) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (hashCnt - 1))
    println(lastAdd)
    Console.flush
  }
}

object Main extends App {

  val s = readLine.split("").filter(_ != "")
  val total = s.size
  val open = s.count(_ == "(")
  val close = s.count(_ == ")")
  val hashes = total - (open + close)

  if((open - close) < hashes) {
    println("-1")
    System.exit(0)
  }

  val init = (0, 0, List[Int]())
  val (sum, _, steps) = s.foldLeft(init)({
    case ((sumAcc, hashesAcc, stepsAcc), i) =>
     i match {
        case "(" => (sumAcc + 1, hashesAcc, stepsAcc)
        case ")" =>
          if(sumAcc == 0) {
            println("-1")
            System.exit(0)
            (sumAcc, hashesAcc, stepsAcc)
          } else {
            (sumAcc-1, hashesAcc, stepsAcc)
          }
       case "#" =>
          if(sumAcc == 0) {
            println("-1")
            System.exit(0)
            (sumAcc, hashesAcc, stepsAcc)
          } else if(hashesAcc == hashes - 1) {
            val add = (open - close) - (hashes - 1)
            if(sumAcc < add) {
              println("-1")
              System.exit(0)
              (sumAcc, hashesAcc, stepsAcc)
            } else {
              (sumAcc - add, hashesAcc + 1, add :: stepsAcc)
            }
          } else {
            (sumAcc - 1, hashesAcc + 1, 1 :: stepsAcc)
         }
     }
  })

   if(sum == 0) {
     steps.reverse foreach println
   } else {
     println("-1")
   }

}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    def zeroFixer (l : List[Int], acc: Int) : List[Int] = {
      l match {
        case x :: Nil => acc + x :: Nil
        case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)
        case Nil => Nil
      }
    }

    def stringFiller (hashes: List[Int], str: List[Char]) : List[Char] = {
      str match {
          case '#' :: tail => (")" * hashes.head).toCharArray.toList ::: stringFiller(hashes.tail, tail)
          case x :: tail => x :: stringFiller(hashes, tail)
          case Nil => Nil
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem
    val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)
    val charFilled = stringFiller(hashRankDiffFixed, chars)
    val strFilledValidation = balanceChecker(charFilled, 0)

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    println(hashRankDiffFixed)
    println(charFilled.mkString)
    println(strFilledValidation)
    */

    if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

import scala.annotation.tailrec

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], level : Int) : List[Int] = {
      @tailrec
      def inner (x: List[Char], level : Int, acc : List[Int] = Nil) : List[Int] = {
        x match {
          case '(' :: tail => inner(tail, level + 1, level + 1 :: acc)
          case ')' :: tail => inner(tail, level - 1, level - 1 :: acc)
          case _ :: tail => inner(tail, level, level :: acc)
          case Nil => acc.reverse
        }
      }
      inner(x, level, Nil)
    }

    @tailrec def zeroFixer (l : List[Int], acc: Int, accList : List[Int] = Nil) : List[Int] = {
      l match {
        case x :: Nil => (acc + x :: accList).reverse
        case x :: tail => zeroFixer(tail, acc + x - 1, 1 :: accList)
        case Nil => accList.reverse
      }
    }

    @tailrec def stringFiller (hashes: List[Int], str: List[Char], acc : List[Char] = Nil) : List[Char] = {
      str match {
          case '#' :: tail => stringFiller(hashes.tail, tail, (")" * hashes.head).toCharArray.toList ::: acc)
          case x :: tail => stringFiller(hashes, tail, x :: acc)
          case Nil => acc.reverse
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem
    val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)
    val charFilled = stringFiller(hashRankDiffFixed, chars)
    val strFilledValidation = balanceChecker(charFilled, 0)

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    println(hashRankDiffFixed)
    println(charFilled.mkString)
    println(strFilledValidation)
    */

    if (hashRankDiffFixed.exists(_ <= 0) || strFilledValidation.last != 0 || strFilledValidation.exists(_ < 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

object Solution extends App {
  def check(str: String) = {
    var open = 0
    str.foldLeft(0) {
      case (-1, el) => -1
      case (x, ')') => x - 1
      case (x, '(') => x + 1
    }
  }

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val r = str.lastIndexOf("#")
  val first = str.take(r).replace('#', ')')
  val t = check(first)
  val open = str.count(_ == '(')
  if (t < 1)
    println(-1)
  else {
    val count = str.count(_ == '#')
    val nStr = first + (")" * Math.max(1, 2 * open - str.length + 1)) + str.drop(r + 1)
    if (check(nStr) == 0) {
      println((1 to count - 1).map(_ => 1).mkString("\n"))
      println(2 * open - str.length + 1)
    } else {
      println(-1)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    def zeroFixer (l : List[Int], acc: Int) : List[Int] = {
      l match {
        case x :: Nil => acc + x :: Nil
        case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)
        case Nil => Nil
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem
    val hashRankDiffFixed = zeroFixer(hashRankDiffFull, 0)

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    println(hashRankDiffFixed)
    */

    if (hashRankDiffFull.exists(_ < 0) || hashRankDiffFixed.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFixed) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {
      out.println(-1)
      return
    }

    if (hashRankDiffButLast.count(_ == 0) < lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
      */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRankDiffButLast.count(_ == 0) < lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum
    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    val str_adapted = str.replaceAll("##", "#(#)")

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str_adapted.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum
    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*
    println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    def zeroFixer (l : List[Int], acc: Int) : List[Int] = {
      l match {
        case x :: Nil => acc + x :: Nil
        case x :: tail => 1 :: zeroFixer(tail, acc + x - 1)
        case Nil => Nil
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks.last - hashRankDiffButLast.sum

    if (hashRanks.last < charRanks.last) {
      out.println(-1)
      return
    }

    /*println(chars)
    println(charRanks)
    println(hashRankDiffButLast :+ lastItem)
    */

    val hashRankDiffFull = zeroFixer(hashRankDiffButLast :+ lastItem, 0)

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#") || str.endsWith("(")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {
      out.println(-1)
      return
    }

    if (hashRankDiffButLast.count(_ == 0) <= lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
      */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#")) {
      out.println("-1")
      return
    }

    val str_adapted = str.replaceAll("##", "#(#)")

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case '#' :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str_adapted.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    val hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    val lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum
    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*
    println(chars)
    println(charRanks)
    println(hashRankDiffFull)
    */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

import java.io.InputStream
import java.io.PrintStream
import java.util.Scanner

object C_Treasure {

  def main(args: Array[String]) {
    parseSolveAndPrint(System.in, System.out)
  }

  def parseSolveAndPrint(in: InputStream, out: PrintStream): Unit = {
    val scanner = new Scanner(in)
    val str = scanner.next()

    if (str.startsWith("#")) {
      out.println("-1")
      return
    }

    def balanceChecker (x: List[Char], b : Int) : List[Int] = {
      x match {
          case '(' :: tail => b + 1 :: balanceChecker(tail, b + 1)
          case ')' :: tail => b - 1 :: balanceChecker(tail, b - 1)
          case _ :: tail => b :: balanceChecker(tail, b)
          case Nil => List.empty
      }
    }

    val chars = str.toCharArray.toList
    val charRanks = balanceChecker(chars, 0)

    val hashRanks = chars.zip(charRanks).filter(_._1 == '#').map(_._2)
    var hashRankDiffButLast = hashRanks.zip(hashRanks.drop(1)).map(x => x._2 - x._1)
    var lastItem = charRanks(charRanks.size - 1) - hashRankDiffButLast.sum

    if (hashRanks(hashRanks.size - 1) < charRanks(charRanks.size - 1)) {
      out.println(-1)
      return
    }

    if (hashRankDiffButLast.count(_ == 0) < lastItem) {
      lastItem -= hashRankDiffButLast.count(_ == 0)
      hashRankDiffButLast = hashRankDiffButLast.map(x => if (x == 0) 1 else x)
    }

    val hashRankDiffFull = hashRankDiffButLast :+ lastItem

    /*println(chars)
    println(charRanks)
    println(hashRankDiffFull)
      */

    if (hashRankDiffFull.exists(_ <= 0)) {
      out.println(-1)
    } else for (x <- hashRankDiffFull) {
      out.println(x)
    }
  }
}

object Solution extends App {
  def check(str: String) = {
    var open = 0
    str.foldLeft(0) {
      case (-1, el) => -1
      case (x, ')') => x - 1
      case (x, '(') => x + 1
    }
  }

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val r = str.lastIndexOf("#")
  val first = str.take(r).replace('#', ')')
  val t = check(first)
  val open = str.count(_ == '(')
  if (t == -1)
    println(-1)
  else {
    val count = str.count(_ == '#')
    val nStr = first + (")" * (2 * open - str.length + 1)) + str.drop(r + 1)
    if (check(nStr) == 0) {
      println((1 to count - 1).map(_ => 1).mkString("\n"))
      println(2 * open - str.length + 1)
    } else {
      println(-1)
    }
  }
}

object Solution extends App {
  def check(str: String) = {
    var open = 0
    str.foldLeft(0) {
      case (-1, el) => -1
      case (x, ')') => x - 1
      case (x, '(') => x + 1
    }
  }

  val in = scala.io.Source.stdin.getLines()
  val str = in.next()
  val r = str.lastIndexOf("#")
  val first = str.take(r).replace('#', ')')
  val t = check(first)
  val open = str.count(_ == '(')
  if (t < 1)
    println(-1)
  else {
    val count = str.count(_ == '#')
    val nStr = first + (")" * (2 * open - str.length + 1)) + str.drop(r + 1)
    if (check(nStr) == 0) {
      println((1 to count - 1).map(_ => 1).mkString("\n"))
      println(2 * open - str.length + 1)
    } else {
      println(-1)
    }
  }
}

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

object A 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 s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false
  var lastAdd = 0

  val lastHash = s.lastIndexOf('#')
  val hashCnt = s.count(_ == '#')
  val openCnt = s.count(_ == '(')
  val closeCnt = s.count(_ == ')')

  for (i <- s.indices) s(i) match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      lastAdd = if (i == lastHash) openCnt - closeCnt - hashCnt + 1 else 1
      cntsAdd += lastAdd
      cntClose += lastAdd
      if (cntClose > cntOpen) bad = true
  }

  if (bad || cntClose > cntOpen || lastAdd == 0) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (hashCnt - 1))
    println(lastAdd)
    Console.flush
  }
}

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

object A 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 s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false

  for (c <- s) c match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      cntsAdd += 1
      cntClose += 1
      if (cntClose > cntOpen) bad = true
  }

  if (bad) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (cntsAdd - 1))
    if (cntsAdd > 0) println(cntOpen - cntClose + 1)
    Console.flush
  }
}

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

object A 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 s = readLine

  var cntsAdd = 0
  var cntOpen = 0
  var cntClose = 0
  var bad = false
  var lastAdd = 0

  val lastHash = s.lastIndexOf('#')
  val hashCnt = s.count(_ == '#')
  val openCnt = s.count(_ == '(')
  val closeCnt = s.count(_ == ')')

  for (i <- s.indices) s(i) match {
    case '(' =>
      cntOpen += 1
    case ')' =>
      cntClose += 1
      if (cntClose > cntOpen) bad = true
    case '#' =>
      lastAdd = if (i == lastHash) math.max(1, openCnt - closeCnt - cntsAdd + 1) else 1
      cntsAdd += lastAdd
      cntClose += lastAdd
      if (cntClose > cntOpen) bad = true
  }

  if (bad) println(-1)
  else {
    Console.setOut(new java.io.BufferedOutputStream(Console.out))
    print("1\n" * (hashCnt - 1))
    println(lastAdd)
    Console.flush
  }
}


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

import scala.annotation.tailrec

object D1 {
  def solve(in: Input, out: PrintWriter): Unit = {
    val n = in.nextInt()
    val arr = Array.fill(n)(in.nextInt())
    java.util.Arrays.sort(arr)
    for (i <- 1 until arr.length by 2) {
      val tmp = arr(i - 1)
      arr(i - 1) = arr(i)
      arr(i) = tmp
    }
    out.println((n - 1) / 2)
    out.println(arr.mkString(" "))
  }

  private def makeTests(): IndexedSeq[(String, String, String)] = IndexedSeq(
    ("5\n1 2 3 4 5", "2\n2 1 4 3 5 ", "Sample"),
    ("1\n1", "0\n1", "Size 1"),
    ("2\n1 2", "0\n2 1", "Size 2"),
    ("3\n1 2 3", "1\n2 1 3", "Size 3"),
    ("4\n1 2 3 4", "1\n2 1 4 3", "Size 4"),
  )

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

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

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

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

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

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

  val bn = Array.ofDim[Int](n)

  bn(0) = an(0)
  (1 until n).foreach {
    case i if i % 2 == 0 => bn(i) = an(i - 1)
    case i => bn(i) = an((n - 1) min (i + 1))
  }

  println((n - 1) / 2)
  println(bn.mkString(" "))
}

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

  if (n <= 2) {
    println(0)
    println(an.mkString(" "))
  } else {
    println((n - 1) / 2)

    val bn = Array.ofDim[Int](n)

    bn(0) = an(0)
    (1 until n).foreach {
      case i if i % 2 == 0 => bn(i) = an(i - 1)
      case i => bn(i) = an((n - 1) min (i + 1))
    }

    println(bn.mkString(" "))
  }
}

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

  val n  = readInt()
  val an = readLine().split(" ").map(_.toInt).sorted(Ordering.Int.reverse)

  if (n <= 2) {
    println(n)
    println(an.mkString(" "))
  } else {
    println((n - 1) / 2)

    val bn = Array.ofDim[Int](n)

    bn(0) = an(0)
    (1 until n).foreach {
      case i if i % 2 == 0 => bn(i) = an(i - 1)
      case i => bn(i) = an((n - 1) min (i + 1))
    }

    println(bn.mkString(" "))
  }
}


object A extends App {

  lazy val Mod = 1000000007L

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n   = nextInt()
    val ans = (3 to 2 * n).foldLeft(1L)((f, i) => (f * i) % Mod)

    out.println(ans)
  }

  out.flush()

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

}

import scala.io.StdIn._

object A extends App {
  def factorial(n: Long): Long = {
    var f = 1L
    for(i <- 3 to n.toInt)
      f = (f * i) % 1000000007
    f
  }

  (1 to readInt()).foreach(_ => {
    println(((factorial(2L*readLong()))))
  })
}

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

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

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

    val mod = 1000000007
    var d = new Array[Long](100010)
    d(1) = 1
    for (i <- 2 to 100000) {
        d(i) = d(i-1) * (2*i-1).toLong
        d(i) %= mod
        d(i) *= (2*i).toLong
        d(i) %= mod
    }

    val t = readInt()
    for (tt <- 1 to t) {
        val n = readInt()
        writer.println(d(n))
    }
    writer.flush()
}

object A extends App {

  lazy val Mod = 1000000007L

  import InOut._

  val t = nextInt()

  (0 until t).foreach { _ =>
    val n   = nextInt()
    val ans = (3 to n).foldLeft(1L)((f, i) => (f * i) % Mod)

    out.println(ans)
  }

  out.flush()

  final object InOut {
    val in  = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    val out = new java.io.PrintWriter(System.out, false)

    def nextInt()        = Integer.parseInt(nextToken())
    def nextInts(n: Int) = Array.fill(n)(nextInt())

    def nextLong()        = java.lang.Long.parseLong(nextToken())
    def nextLongs(n: Int) = Array.fill(n)(nextLong())

    def nextBig()        = BigInt(nextToken())
    def nextBigs(n: Int) = Array.fill(n)(nextBig())

    def nextLine() = in.readLine()

    private[this] var tokenizer: java.util.StringTokenizer = _

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

}


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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, f = read[Int]

    val data = read[Seq, (Long, Long)](n) map {
      case (p, c) =>
        val sold = p min c
        val soldIfSale = 2*p min c
        (soldIfSale, sold, soldIfSale - sold)
    }

    val (sale, regular) = data.sortBy(_._3)(desc).splitAt(f)

    val ans = sale.sumWith(_._1) + regular.sumWith(_._2)

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

/**
  * @author tdx
  */
object Main {
  import scala.collection.mutable.ArrayBuffer
  import scala.io.StdIn._
  import scala.math._

  def parts(line : String) = {
    line.split(" ").map(_.toInt)
  }

  def cost(pair: (Int, Int)) = min(pair._1, pair._2)

  def main(args: Array[String]): Unit = {
    val p = parts(readLine())
    val (n, f) = (p(0), p(1))
    val arr = ArrayBuffer[(Int, Int)]()

    for (_ <- 1 to n) {
      val p = parts(readLine())
      val (ki, li) = (p(0), p(1))
      arr.append((ki, li))
    }

    val sorted = arr.sortBy {
      case (ki, li) => -(cost(2*ki, li) - cost(ki, li))
    }

    val all = arr.foldLeft(0L)((total, pair) => total + cost(pair)) +
      sorted.take(f).foldLeft(0L)((total, pair) => total + cost((2 * pair._1, pair._2)) - cost(pair))

    println(all)
  }

}

object B extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toLong))
  val Array(n, f) = input(0).map(_.toInt)
  val days = input.drop(1)
  def doublingDiff(a: Array[Long]): Long = a match {
    case Array(prod, cust) =>
      val normalSale = cust min prod
      val doubleSale = cust min (prod * 2)
      doubleSale - normalSale
  }
  val fSum = if (f >= (n / 2))
    -days.view.map(a => -doublingDiff(a)).sorted.take(f).sum
  else
    days.view.map(a => doublingDiff(a)).sorted.drop(n - f).sum
  val normSum = days.map(_.min).sum
  print(fSum + normSum)
}

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, f) = readInts(2)
  case class Day(k: Long, l: Long)

  def sell(k: Long, l: Long) = {
    Math.min(k, l)
  }

  val days = Array.fill(n) {
    val Array(k, l) = readLongs(2)
    Day(k, l)
  }.sortBy {
    case Day(k, l) =>
      sell(2 * k, l) - sell(k, l)
  }.reverse

  val sale = days.take(f)
  val rest = days.drop(f)
  val res1 = sale.map {
    case Day(k, l) =>
      sell(2 * k, l)
  }.sum
  val res2 = rest.map {
    case Day(k, l) =>
      sell(k, l)
  }.sum

  println(res1 + res2)
}

object B extends App {
  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toInt))
  val Array(n, f) = input(0)
  val days = input.drop(1)
  val sorted = days.sortBy{ case Array(prod, cust) =>
    val normalSale = cust min prod
    val doubleSale = cust min (prod * 2)
    -(doubleSale - normalSale)
  }

  val sumOne = sorted.take(f).map { case Array(prod, cust) =>
    cust min (prod * 2)
  }.sum

  val sumTwo = sorted.drop(f).map { case Array(prod, cust) =>
    cust min prod
  }.sum
  print(sumOne + sumTwo)
}

object B extends App {

  import scala.io.Source

  val input = Source.fromInputStream(System.in).getLines.toVector.map(_.split(" ").map(_.toLong))
  val Array(n, f) = input(0).map(_.toInt)
  val days = input.drop(1)
  val normSum = days.map(_.min).sum
  if (f >= (n / 2)) {
    val fSumNeg = days.view.map{ case Array(prod, cust) =>
      val normalSale = cust min prod
      val doubleSale = cust min (prod * 2)
      -(doubleSale - normalSale)
    }.sorted.take(f).sum
    print(-fSumNeg + normSum)
  } else {
    val fSum = days.view.map{ case Array(prod, cust) =>
      val normalSale = cust min prod
      val doubleSale = cust min (prod * 2)
      doubleSale - normalSale
    }.sorted.drop(f).sum
    print(fSum + normSum)
  }
}

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

  override def apply(io: IO) = {import io.{read, readAll, write, writeAll, writeLine}
    val n, f = read[Int]

    val data = read[Seq, (Int, Int)](n) map {
      case (p, c) =>
        val sold = p min c
        val soldIfSale = 2*p min c
        (soldIfSale, sold)
    }

    val (sale, regular) = data.sorted(desc[(Int, Int)]).splitAt(f)

    val ans = sale.sumWith(_._1) + regular.sumWith(_._2)

    write(ans)
  }
}
/****************************[Ignore Template Below]****************************************/
trait CodeForcesApp {
  lazy val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: => Any): Unit = if (!isOnlineJudge) println(x)
  def apply(io: IO): io.type
  def main(args: Array[String]): Unit = this(new IO(System.in, System.out)).close()
}
object Utils {
  import scala.collection.mutable, mutable.{Map => Dict}
  implicit class GenericExtensions[A](val a: A) extends AnyVal {
    def in(set: collection.Set[A]): Boolean = set(a)
    def some: Option[A] = Some(a)
    def partialMatch[B](f: PartialFunction[A, B]): Option[B] = f lift a
  }
  implicit class TraversableExtensions[A, C[X] <: Traversable[X]](val t: C[A]) extends AnyVal {
    def onlyElement: A = assuming(t.size == 1)(t.head)
    def groupByIdentifier[K](f: A => K): Map[K, A] = t.groupBy(f).mapValues(_.onlyElement)
    def duplicates(implicit b: C of A): C[A] = {
      val elems = mutable.Set.empty[A]
      (t collect {case i if !elems.add(i) => i}).to[C]
    }
    def sumWith[B](f: A => B)(implicit n: Numeric[B]): B = t.foldLeft(n.zero) {case (p, i) => n.plus(p, f(i))}
    def maxWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.max)
    def minWith[B](f: A => B)(implicit ord: Ordering[B]): Option[B] = t.view.map(f).reduceOption(ord.min)
    def zipWith[B](f: A => B)(implicit b: C of (A, B)): C[(A, B)] = (t map {i => i -> f(i)}).to[C]
    def mapTo[B](f: A => B)(implicit b: C of (A, B)): Map[A, B] = zipWith(f).toUniqueMap
    def whenNonEmpty[B](f: t.type => B): Option[B] = when(t.nonEmpty)(f(t))  // e.g. grades.whenNonEmpty(_.max)
    def collectFirst[B](f: PartialFunction[A, Option[B]]): Option[B] = t.view collect f collectFirst {case Some(x) => x}
    def toMutableMultiSet: Dict[A, Int] = {
      val c = map[A] to 0
      t.foreach(i => c(i) += 1)
      c
    }
    def toMultiSet: Map[A, Int] = toMutableMultiSet.toMap withDefaultValue 0
    def X[B](s: Traversable[B]): Iterator[(A, B)] = for {a <- t.toIterator; b <- s} yield (a, b)
  }
  implicit class ArrayExtensions[A <: AnyRef](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = java.util.Arrays.sort(a, from, until, cmp) //sort [from, until)
  }
  implicit class ArrayExtensions2[A](val a: Array[A]) extends AnyVal {
    def sort(from: Int, until: Int)(implicit cmp: Ordering[A]): Unit = a.view(from, until).sorted.copyToArray(a, from)
  }
  implicit class SeqExtensions[A, C[X] <: Seq[X]](val s: C[A]) extends AnyVal {
    def isRotationOf(t: Seq[A]): Boolean = s ++ s containsSlice t
  }
  implicit class PairExtensions[A, B](val p: (A, B)) extends AnyVal {
    def key = p._1
    def value = p._2
  }
  implicit class PairsExtensions[A, B, C[X] <: Traversable[X]](t: C[(A, B)]) {
    def toUniqueMap: Map[A, B] = t.groupByIdentifier(_.key).mapValues(_.value)
    def toMultiMap(implicit b: C of B): Map[A, C[B]] = t.groupBy(_.key).mapValues(_.map(_.value).to[C])
    def swap(implicit b: C of (B, A)): C[(B, A)] = t.map(_.swap).to[C]
  }
  implicit class MapExtensions[K, V, C[X, Y] <: Map[X, Y]](val m: C[K, V]) extends AnyVal {
    def lastKeyOption: Option[K] = m.lastOption.map(_.key)
    def firstKeyOption: Option[K] = m.headOption.map(_.key)
    def invert: Map[V, Set[K]] = m.toSet[(K, V)].swap.toMultiMap
    def mapKeys[K2](f: K => K2): Map[K2, V] = m map {case (k, v) => f(k) -> v}
    def toMutable: Dict[K, V] = Dict.empty[K, V] ++ m
    def mapValuesSafely[V2](f: V => V2): Map[K, V2] = m.mapValues(f).view.force //Hack to get around https://issues.scala-lang.org/browse/SI-4776
  }
  implicit class MutableMapExtensions[K, V](val m: mutable.Map[K, V]) extends AnyVal {
    def removeLast(): Option[(K, V)] = m.lastOption.map(removeNode)
    def removeFirst(): Option[(K, V)] = m.headOption.map(removeNode)
    private def removeNode(kv: (K, V)): (K, V) = {
      m -= kv.key
      kv
    }
  }
  implicit class SetExtensions[A, C[A] <: Set[A]](val s: C[A]) extends AnyVal {
    def notContains(x: A): Boolean = !(s contains x)
    def toMutable = mutable.Set.empty[A] ++ s
  }
  implicit class IterableExtensions[A, C[A] <: Seq[A]](val s: C[A]) extends AnyVal {
    def indicesWhere(f: A => Boolean): Seq[Int] = s.zipWithIndex.collect {case (a, i) if f(a) => i}
    def deleteAtIndex(i: Int, howMany: Int = 1) = s.patch(i, Nil, howMany)
    def insertAtIndex(i: Int, items: Seq[A]) = s.patch(i, items, 0)
    def findWithIndex(f: A => Boolean): Option[(A, Int)] = s.zipWithIndex find {case (a, _) => f(a)}
    def foldUntil[B](z: B)(f: (B, A) => B)(c: B => Boolean): Option[(B, Int)] = s.view.scanLeft(z)(f).findWithIndex(c)
  }
  implicit class BooleanExtensions(val x: Boolean) extends AnyVal {
    def to[A](implicit n: Numeric[A]) = if(x) n.one else n.zero
    def toEnglish = if(x) "YES" else "NO"
  }
  implicit class IntExtensions(val x: Int) extends AnyVal {
    import java.lang.{Integer => JInt}
    def withHighestOneBit: Int = JInt.highestOneBit(x)
    def withLowestOneBit: Int = JInt.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JInt.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JInt.numberOfTrailingZeros(x)
    def bitCount: Int = JInt.bitCount(x)
    def setLowestBits(n: Int): Int = x | (left(n) - 1)
    def clearLowestBits(n: Int): Int = x & left(n, ~0)
    def setBit(i: Int, set: Boolean): Int = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Int = x | left(i)
    def clearBit(i: Int): Int = x & ~left(i)
    def toggleBit(i: Int): Int = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Int = 1) = assuming(bits >= 0 && bits < JInt.SIZE)(num << bits)
    def X(y: Int): Iterator[(Int, Int)] = until(x) X until(y)
  }
  implicit class LongExtensions(val x: Long) extends AnyVal {
    import java.lang.{Long => JLong}
    def withHighestOneBitSet: Long = JLong.highestOneBit(x)
    def withLowestOneBitSet: Long = JLong.lowestOneBit(x)
    def numberOfLeadingZeroes: Int = JLong.numberOfLeadingZeros(x)
    def numberOfTrailingZeroes: Int = JLong.numberOfTrailingZeros(x)
    def bitCount: Int = JLong.bitCount(x)
    def setLowestBits(n: Int): Long = x | (left(n) - 1)
    def clearLowestBits(n: Int): Long = x & left(n, ~0L)
    def setBit(i: Int, set: Boolean): Long = if (set) setBit(i) else clearBit(i)
    def setBit(i: Int): Long = x | left(i)
    def clearBit(i: Int): Long = x & ~left(i)
    def toggleBit(i: Int): Long = x ^ left(i)
    def testBit(i: Int): Boolean = ((x >> i) & 1) == 1
    private def left(bits: Int, num: Long = 1L) = assuming(bits >= 0 && bits < JLong.SIZE)(num << bits)
  }
  implicit class NumericExtensions[A](val x: A)(implicit n: Numeric[A]) {
    import Numeric.Implicits._
    def **(i: Int): A = if (i == 0) n.one else {
      val h = x ** (i/2)
      if (i%2 == 0) h * h else h * h * x
    }
    def distance(y: A) = (x - y).abs()
    def nonNegative: Option[A] = when(n.gteq(x, n.zero))(x)
    def whenNegative(f: => A): A = nonNegative getOrElse f   //e.g. students indexOf "Greg" whenNegative Int.MaxValue
  }
  implicit class IntegralExtensions[A](val x: A)(implicit n: Integral[A]) {
    import scala.collection.immutable.NumericRange, Integral.Implicits._
    def mod(y: A): A = x - ((x / y) * y) //(x/y)*y + (x mod y) == x
    def -->(y: A): NumericRange.Inclusive[A] = NumericRange.inclusive(x, y, if (n.lteq(x, y)) n.one else -n.one)
    def ceilDiv(y: A): A = if (mod(y) == n.zero) x/y else n.one + (x/y)
  }
  implicit def toPoint[A](p: (A, A))(implicit n: Numeric[A]) = new java.awt.geom.Point2D.Double(n.toDouble(p._1), n.toDouble(p._2))
  def desc[A: Ordering]: Ordering[A] = asc[A].reverse  //e.g. students.sortBy(_.height)(desc)
  def asc[A](implicit order: Ordering[A]): Ordering[A] = order
  def map[K] = new {
    def to[V](default: => V): Dict[K, V] = using(_ => default)
    def using[V](f: K => V): Dict[K, V] = new mutable.HashMap[K, V]() {
      override def apply(key: K) = getOrElseUpdate(key, f(key))
    }
  }
  def newMultiMap[K, V] = map[K] to mutable.Set.empty[V]
  def memoize[A, B](f: A => B): A ==> B = map[A] using f
  implicit class FuzzyDouble(val x: Double) extends AnyVal {
    def  >~(y: Double) = x > y + eps
    def >=~(y: Double) = x >= y + eps
    def  ~<(y: Double) = y >=~ x
    def ~=<(y: Double) = y >~ x
    def  ~=(y: Double) = (x distance y) <= eps
  }
  def toPolygon(points: Traversable[(Int, Int)]): java.awt.Polygon = {
    val (xs, ys) = points.unzip
    new java.awt.Polygon(xs.toArray, ys.toArray, points.size)
  }
  def toShape(points: Traversable[(Double, Double)]): java.awt.geom.GeneralPath = {
    val shape = new java.awt.geom.GeneralPath()
    points.headOption foreach {case (x, y) => shape.moveTo(x, y)}
    points.tail foreach {case (x, y) => shape.lineTo(x, y)}
    shape.closePath()
    shape
  }
  def until(until: Int): Range = 0 until until
  def not[A](f: A => Boolean): A => Boolean = {x: A => !f(x)}
  def assuming[A](cond: => Boolean)(f: => A): A = {require(cond); f}
  @inline def when[A](check: Boolean)(f: => A): Option[A] = if (check) f.some else None
  def repeat[U](n: Int)(f: => U): Unit = (1 to n).foreach(_ => f)
  type of[C[_], A] = scala.collection.generic.CanBuild[A, C[A]]
  type ==>[A, B] = collection.Map[A, B]
  val mod: Int = (1e9 + 7).toInt
  val eps: Double = 1e-9
}
/***********************************[Scala I/O]*********************************************/
import Utils._, java.io._, java.util.StringTokenizer

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

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

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

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

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

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

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

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

  override def flush() = printer.flush()
  def close() = {
    flush()
    in.close()
    printer.close()
  }
}
object IO {
  class Read[A](val apply: IO => A) {
    def map[B](f: A => B): Read[B] = new Read(apply andThen f)
  }
  object Read {
    implicit def collection[C[_], A: Read](implicit b: C of A): Read[C[A]]         = new Read(r => r.read[C, A](r.read[Int]))
    implicit val string                                       : Read[String]       = new Read(_.next())
    implicit val char                                         : Read[Char]         = string.map(_.toTraversable.onlyElement)
    implicit val int                                          : Read[Int]          = string.map(_.toInt)
    implicit val long                                         : Read[Long]         = string.map(_.toLong)
    implicit val bigInt                                       : Read[BigInt]       = string.map(BigInt(_))
    implicit val double                                       : Read[Double]       = string.map(_.toDouble)
    implicit val bigDecimal                                   : Read[BigDecimal]   = string.map(BigDecimal(_))
    implicit def tuple2[A: Read, B: Read]                     : Read[(A, B)]       = new Read(r => (r.read[A], r.read[B]))
    implicit def tuple3[A: Read, B: Read, C: Read]            : Read[(A, B, C)]    = new Read(r => (r.read[A], r.read[B], r.read[C]))
    implicit def tuple4[A: Read, B: Read, C: Read, D: Read]   : Read[(A, B, C, D)] = new Read(r => (r.read[A], r.read[B], r.read[C], r.read[D]))
    implicit val boolean                                      : Read[Boolean]      = string map {s =>
      s.toLowerCase match {
        case "yes" | "true" | "1" => true
        case "no" | "false" | "0" => false
        case _ => s.toBoolean
      }
    }
  }
}

/**
  * @author tdx
  */
object Main {
  import scala.collection.mutable.ArrayBuffer
  import scala.io.StdIn._
  import scala.math._

  def parts(line : String) = {
    line.split(" ").map(_.toInt)
  }

  def cost(pair: (Int, Int)) = min(pair._1, pair._2)

  def main(args: Array[String]): Unit = {
    val p = parts(readLine())
    val (n, f) = (p(0), p(1))
    val arr = ArrayBuffer[(Int, Int)]()

    for (_ <- 1 to n) {
      val p = parts(readLine())
      val (ki, li) = (p(0), p(1))
      arr.append((ki, li))
    }

    val sorted = arr.sortBy {
      case (ki, li) => -(cost(2*ki, li) - cost(ki, li))
    }

    val all = arr.foldLeft(0)((total, pair) => total + cost(pair)) +
      sorted.take(f).foldLeft(0)((total, pair) => total + cost((2 * pair._1, pair._2)) - cost(pair))

    println(all)
  }

}


//package codeforces.contests._1487

object MinimumTies {

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

        val EachTeamWins = (n - 1) / 2

        val teamWins = Array.fill(n + 1)(0)

        def drawCheck(i: Int, j: Int): Boolean = n % 2 == 0 && (j - i) == n / 2

        {
          for {
            i <- 1 to n
            j <- i + 1 to n
          } yield {
            if (drawCheck(i, j)) 0
            else if (teamWins(i) < EachTeamWins) {
              teamWins(i) += 1
              1
            } else if (teamWins(j) < EachTeamWins) {
              teamWins(j) += 1
              -1
            } else {
              0
            }
          }
        }.mkString(" ")
      }
    }.mkString("\n"))
  }
}

import scala.collection.mutable.ArrayBuffer

object C {

  import InOut._

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

    for (_ <- 1 to nextInt) {
      val n = nextInt
      val games = Array.fill(n, n)(0)
      val scores = ArrayBuffer.empty[Int]
      for (i <- 0 until n) {
        var res = if (i % 2 == 0) 1 else -1
        for (j <- 0 until n) {
          if (i != j) {
            var r = 0
            if ((n % 2 == 1 || (i != n - j - 1))) {
              r = res
              res = -res
            }
            if (i < j) scores += r
            games(i)(j) = r
          }
        }
      }

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

    out.flush()
  }

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

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

    def nextInt = Integer.parseInt(nextToken)

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

    def nextBig = BigInt(nextToken)

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

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

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

    def nextLine = in.readLine
  }

}

object C {
  import scala.io.{StdIn => in}

  def main(args: Array[String]): Unit = {
    val tests = in.readInt()
    (1 to tests).foreach { _ =>
      val n = in.readInt() - 1
      val wins = (0 until n/2).map(_ => 1) ++ (if (n % 2 == 0) Seq() else Seq(0)) ++ (0 until n/2).map(_ => -1)
      println((0 to n).map(i => wins.dropRight(i).mkString(" ")).mkString(" "))
    }
  }
}

//package codeforces.contests._1487

object MinimumTies {

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

        val EachTeamWins = (n - 1) / 2

        val teamWins = Array.fill(n + 1)(0)

        {
          for {
            i <- 1 to n
            j <- i + 1 to n
          } yield {
            if (teamWins(i) < EachTeamWins) {
              teamWins(i) += 1
              1
            } else if (teamWins(j) < EachTeamWins) {
              teamWins(j) += 1
              -1
            } else {
              0
            }
          }
        }.mkString(" ")
      }
    }.mkString("\n"))
  }
}


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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)
    out.println(processedStations(0)._2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    (Math.sqrt(dist(station, 0, x, y)) * busSpeed + Math.abs(station) * manSpeed, dist(station, 0, x, y))
  }

  def dist(x: Double, y: Double, x1: Double, y1: Double): Double = {
    (x - x1) * (x - x1) + (y - y1) * (y - y1)
  }

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

import scala.io._
import scala.collection.mutable._
import java.util.StringTokenizer

object HelloWorld {

  def main(args: Array[String]): Unit = {
    var Array(n, vb, vs) = readLine.split(" ").map(_.toDouble);
    var x = readLine.split(" ").map(_.toDouble);
    var Array(xu, yu) = readLine.split(" ").map(_.toDouble);
    for (i <- 1 until x.length - 1) {
      var tc = math.sqrt(math.pow(xu - x(i), 2) + math.pow(yu, 2)) / vs;
      var tn = (x(i + 1) - x(i)) / vb + math.sqrt(math.pow(xu - x(i + 1), 2) + math.pow(yu, 2)) / vs;
      if (tc < tn) {
        println(i + 1);
        return;
      }
    }
    println(x.length);
  }

}

//package me.jetblack.cf

import java.util.Scanner

object BusStop extends App {

  val s = new Scanner(System.in)

  import s._

  val n = nextInt()
  val (vb, vs) = (nextInt().toDouble, nextInt().toDouble)

  val stops = (0 until n).map { _ =>
    (nextInt().toDouble, 0.0)
  }.toArray

  val univ = (nextInt().toDouble, nextInt().toDouble)

  def dist(a: (Double, Double), b: (Double, Double)): Double = math.sqrt((a._1 - b._1) * (a._1 - b._1) + (a._2 - b._2) * (a._2 - b._2))

  var result = Integer.MAX_VALUE.toDouble
  val start = (0.0, 0.0)
  var stopNum = 1
  var sun = Integer.MAX_VALUE.toDouble

  stops.tail.zipWithIndex.map { case (stop, i) =>
    val d = dist(start, stop) / vb + dist(stop, univ) / vs
    val curs = dist(stop, univ)
    if (d <= result && curs < sun) {
      result = d
      stopNum = i + 2
    }
  }

  println(stopNum)

}

object P9B {
    import io.StdIn._
    import Math._

    def main(args:Array[String]) {
        val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}
        val a = readLine.split(' ').map{_.toDouble}
        val Array(xu, yu) = readLine.split(' ').map{_.toDouble}
        println(1.to(a.size - 1).minBy{i => {
            val xs = xu - a(i)
            a(i) / vb + sqrt(xs * xs + yu * yu) / vs - i * 1e-6
        }} + 1)
    }
}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, vb, vs) = in.next().split(' ').map(_.toInt)
  val xs = in.next().split(' ').map(_.toInt)
  val Array(xu, yu) = in.next().split(' ').map(_.toDouble)

  val res = xs.indices.tail.foldLeft(-1, 0d, 0d) {
    case ((-1, _, _), i) =>
      val dx: Double = xs(i) - xu
      (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
    case (acc@(sum, index, length), i) =>
      val dx: Double = xs(i) - xu
      val candidate = (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
      if (candidate._2 < acc._2 || (candidate._2 == acc._2 && candidate._3 < acc._3)) {
        candidate
      }
      else acc
  }

  println(res._1)

}

object Solution extends App {
  val in = io.Source.stdin.getLines()
  val Array(n, vb, vs) = in.next().split(' ').map(_.toInt)
  val xs = in.next().split(' ').map(_.toInt)
  val Array(xu, yu) = in.next().split(' ').map(_.toDouble)

  val res = xs.indices.tail.foldLeft(-1, 0d, 0d) {
    case ((-1, _, _), i) =>
      val dx: Double = xs(i) - xu
      (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
    case (acc@(sum, index, length), i) =>
      val dx: Double = xs(i) - xu
      val candidate = (i + 1, xs(i).toDouble / vb + Math.sqrt(dx * dx + yu * yu) / vs, Math.abs(dx))
      println(acc)
      println(candidate)
      if (candidate._2 < acc._2 || (candidate._2 == acc._2 && candidate._3 < acc._3)) {
        candidate
      }
      else acc
  }

  println(res._1)

}

//package me.jetblack.cf

import java.util.Scanner

object BusStop extends App {

  val s = new Scanner(System.in)

  import s._

  val n = nextInt()
  val (vb, vs) = (nextInt().toDouble, nextInt().toDouble)

  val stops = (0 until n).map { _ =>
    (nextInt().toDouble, 0.0)
  }.toArray

  val univ = (nextInt().toDouble, nextInt().toDouble)

  def dist(a: (Double, Double), b: (Double, Double)): Double = math.sqrt((a._1 - b._1) * (a._1 - b._1) + (a._2 - b._2) * (a._2 - b._2))

  var result = Integer.MAX_VALUE.toDouble
  val start = (0.0, 0.0)
  var stopNum = 1

  stops.tail.zipWithIndex.map { case (stop, i) =>
    val d = dist(start, stop) / vb + dist(stop, univ) / vs
    if (d < result) {
      result = d
      stopNum = i + 2
    }
  }

  println(stopNum)

}

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)
    out.println(processedStations(0)._2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    ((dist(station, 0, x, y) * busSpeed + Math.abs(station) * manSpeed) / (busSpeed * manSpeed), dist(station, 0, x, y))
  }

  def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
  }

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

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zip(Stream from 2).sortWith(customComparator)
    out.println(processedStations(0)._2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    if (!dist(station, 0, x, y).isNaN) ((dist(station, 0, x, y) * busSpeed + Math.abs(station) * manSpeed) / (busSpeed * manSpeed), dist(station, 0, x, y))
    else (Double.MAX_VALUE, Double.MAX_VALUE)
  }

  def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
  }

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

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

object B {

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

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

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

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

  def solve = {
    val n = nextInt
    val busSpeed = nextInt
    val manSpeed = nextInt
    val stations: Array[Int] = new Array[Int](n - 1)
    nextInt
    for (i <- 0 until n - 1) {
      stations(i) = nextInt
    }
    val x = nextInt
    val y = nextInt
    val processedStations = stations.map(X => solver(X, busSpeed, manSpeed, x, y)).zipWithIndex.sortWith(customComparator)
    out.println(processedStations(0)._2 + 2)
  }

  def customComparator(first: ((Double, Double), Int), second: ((Double, Double), Int)) =
    if (first._1._1 == second._1._1) first._1._2 < second._1._2 else first._1._1 < second._1._1

  def solver(station: Int, busSpeed: Int, manSpeed: Int, x: Int, y: Int): (Double, Double) = {
    (dist(station, 0, x, y) / manSpeed + station / busSpeed, dist(station, 0, x, y))
  }

  def dist(x: Int, y: Int, x1: Int, y1: Int): Double = {
    Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
  }

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

object P9B {
    import io.StdIn._
    import Math._

    def main(args:Array[String]) {
        val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}
        val a = readLine.split(' ').map{_.toDouble}
        val Array(xu, yu) = readLine.split(' ').map{_.toInt}
        println(1.to(a.size - 1).minBy{i => {
            val xs = xu - a(i)
            a(i) / vb + sqrt(xs * xs + yu * yu) / vs
        }} + 1)
    }
}

object P9B {
    import io.StdIn._
    import Math._

    def main(args:Array[String]) {
        val Array(n, vb, vs) = readLine.split(' ').map{_.toInt}
        val a = readLine.split(' ').map{_.toInt}
        val Array(xu, yu) = readLine.split(' ').map{_.toInt}
        println(1.to(a.size - 1).minBy{i => {
            val xs = xu - a(i)
            a(i).toDouble / vb + sqrt(xs * xs + yu * yu) / vs
        }} + 1)
    }
}


object Main {
  def main(args: Array[String]) {
    val n = readLine().split(" ").map(_.toInt).head
    val b: Array[(Int,Int)] = readLine().split(" ").map(_.toInt).toArray.zipWithIndex
    val t = b.filter(x => x._1 == x._2).length
    var res = 0
    if (b.exists(x => b(x._1)._1 == x._2 && x._1 != x._2)) {
      res += 2
      res+=t
    } else {
      res={if (t == n) t else t+1}
    }
    println(res)
  }
}

object B {
  def main(args: Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val n = sc.nextInt
    val t = (Nil : Seq[Int]).toBuffer
    for (i <- 1 to n)
      t += sc.nextInt
    var fix = new Array[Boolean](n)
    for (i <- 0 until n)
      if (i == t(i))
        fix(i) = true
    val cnt = fix.filter(_ == true).size
    for (i <- 0 until n)
      if (!fix(i) && !fix(t(i)))
        if (i == t(t(i))) {
          println(cnt + 2)
          return
        }
    if (cnt >= n-1) {
      println(cnt)
      return
    }
    println(cnt + 1)
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(" ").map(_.toInt)
  val res = data.indices.foldLeft((0, 0)) {
    case ((onPlace, add), i) if data(i) == i => (onPlace + 1, add)
    case ((onPlace, 2), i) => (onPlace, 2)
    case ((onPlace, 1), i) if data(data(i)) == i => (onPlace, 2)
    case ((onPlace, _), i) => (onPlace, 1)
  }
  println(res._1 + res._2)
}

object B347 {
  @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)
    val map = input.zipWithIndex.toMap
    var res = map.count{case (x, y) => x == y}
    if(res == input.length) {
      println(res)
    } else {
      var i = 0
      var break = false
      while(!break && i < n) {
        val value = map(map(i))
        if(map(i) != i && value == i) {
          println(res + 2)
          break = true
        }
        i += 1
      }
      if(!break) {
        println(res + 1)
      }
    }
  }
}

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

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  var n = 0
  var e = 1
  0 until N foreach { i =>
    if (A(i) == i) {
      n = n + 1
    }
    else if (A(A(i)) == i) {
      e = 2
    }
  }
  out.println((n + e) min N)
  out.close
}

object Main {
  def main(args: Array[String]) = {
    val n = readInt()
    val a = readLine().split(" ").map(_.toInt)
    val f = a.zipWithIndex.find(t => t._1 != t._2 && t._2 == a(t._1))
    val count = a.zipWithIndex.count(t => t._1 == t._2)
    if (count == n) println(n)
    else f match {
      case None => println(count + 1)
      case Some(_) => println(count + 2)
    }
  }
}

import scala.io.StdIn
/**
  * http://codeforces.com/problemset/problem/347/B
  **/
object FixedPoints {
  def main(args: Array[String]): Unit = {
    StdIn.readLine()
    val numbers = StdIn.readLine().split(" ").map(_.toInt)
    println(nbFixedPoints(numbers))
  }

  private def nbFixedPoints(numbers: Array[Int]): Int = {
    val (same, different) = numbers.zipWithIndex.partition { case (elt, idx) => elt == idx }
    val additional =
      if (different.isEmpty) 0
      else if (different.exists { case (elt, idx) => numbers(elt) == idx }) 2
      else 1
    same.size + additional
  }

  def test() = {
    val inputs = Map(
      Array(0, 1, 3, 4, 2) -> 3,
      Array(0, 1, 5, 3, 4, 2, 7, 6) -> 6,
      Array(0, 1, 5, 3, 4, 2, 7, 6, 8, 9, 10) -> 9
    )
    for ((numbers, expected) <- inputs) {
      assert(nbFixedPoints(numbers) == expected)
    }
  }
}

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

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

  val N = sc.nextInt
  val A = Array.fill(N)(sc.nextInt)

  var n = 0
  var e = 1
  0 until N foreach { i =>
    if (A(i) == i) {
      n = n + 1
    }
    else if (A(A(i)) == i) {
      e = 2
    }
  }
  out.println(n + e)
  out.close
}


object Main extends Solution {
  override def solve(): Any = {
    (1 to nextInt).foreach(_ => println(nextInt.toString.max))
  }
}

trait Solution extends FastIO {
  val cases = 1
  lazy val isLocal: Boolean = sys.props.get("CLown1331").exists(_.toBoolean)
  override val isFileInput: Boolean = isLocal
  override val isFileOutput: Boolean = false

  def debug(x: => Any): Unit = if (isLocal) println(x)

  def solve(): Any

  def main(args: Array[String]): Unit = {
    if (isLocal)
      (1 to cases).foreach(_ => solve())
    else
      solve()
    flush()
  }
}

trait FastIO {

  import java.io._

  val isFileInput = false
  val isFileOutput = false
  val input = "res/in.txt"
  val output = "res/out.txt"

  lazy val bf = new BufferedReader(if (isFileInput) new FileReader(input) else new InputStreamReader(System.in))
  lazy val in = new StreamTokenizer(bf)
  lazy val out = new PrintWriter(if (isFileOutput) new FileWriter(output) else new OutputStreamWriter(System.out))

  def next: String = {
    in.ordinaryChars('0', '9')
    in.wordChars('0', '9')
    in.nextToken()
    in.sval
  }

  def nextInt: Int = {
    in.nextToken()
    in.nval.toInt
  }

  def nextLong: Long = {
    in.nextToken()
    in.nval.toLong
  }

  def nextDouble: Double = {
    in.nextToken()
    in.nval
  }

  def readLine: String = bf.readLine()

  def println(o: Any): Unit = out.println(o)

  def print(o: Any): Unit = out.print(o)

  def printf(s: String, o: Any*): PrintWriter = out.printf(s, o)

  def flush(): Unit = out.flush()
}

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

  val t = readInt()

  (0 until t).foreach { _ =>
    val n  = readLine().split("").map(_.toInt)

    val ans = n.max

    println(ans)
  }
}