import java.util._

object CF268A {

    def main(args: Array[String]) {
        var list1 = Array[Int]()
        var list2 = Array[Int]()
        val in = new Scanner(System.in)

        val n = in.nextInt

        for (i <- 0 to n - 1) {
            list1 = list1 :+ in.nextInt
            list2 = list2 :+ in.nextInt
        }

        var count = 0
        for (i <- 0 to n - 1) {
            for (j <- 0 to n - 1) {
                if (i != j && list2(j) == list1(i)) {
                    count += 1
                }
            }
        }

        println(count)
    }

}

object Two68A 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, Int)](n)
	for (i <- 0 until n) {
		arr(i) = (nextInt, nextInt)
	}
	var sum = 0
	for (i <- 0 until n; j <- i + 1 until n) {
		val x1 = arr(i)
		val x2 = arr(j)
		if (x1._1 == x2._2) sum += 1
		if (x2._1 == x1._2) sum += 1
	}
	println(sum)
	in.close
	out.close
}

import scala.annotation.tailrec
import scala.io.StdIn.readInt
import scala.io.StdIn.readLine

object Main extends App {
  case class Team(homeColor: Int, guestColor: Int)

  val n = readInt()
  val teams = (for {
    _ <- 0 until n
    Array(hColor, gColor) = readLine().split(" ").map(_.toInt)
  } yield Team(hColor, gColor)).toList

  val ans = teams.foldLeft(0)((sum, host) => sum + count(host, teams, 0))
  println(ans)

  @tailrec
  def count(host: Team, others: List[Team], acc: Int): Int = others match {
    case Nil => acc
    case x :: xs =>
      if (x.guestColor == host.homeColor) count(host, xs, acc + 1)
      else count(host, xs, acc)
  }
}

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

object Main extends App {
  val n = StdIn.readInt()
  val array = ArrayBuffer[(Int, Int)]()

  for (_ <- 1 to n) {
    val str = StdIn.readLine().split(" ").map(_.toInt)
    array += ((str(0), str(1)))
  }

  var count = 0

  for (i <- 1 to n) {
    for (j <- (i + 1) to n) {
      if (array(i - 1)._1 == array(j - 1)._2) count += 1
      if (array(i - 1)._2 == array(j - 1)._1) count += 1
    }
  }

  println(count)
}

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, sc.nextInt)
  var cnt = 0
  for(i <- t) for(j <- t) if(i._1 == j._2) cnt += 1
  println(cnt)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  val data = Range(0, n).map{ i => in.next().split(" ")}
  println(data.map(el => data.count{t => t.last == el.head}).sum)
}

object Main {
  def main(args: Array[String]) {
    val n = readLine().toInt
    val h = new Array[Int](n)
    val a = new Array[Int](n)
    for (i <- 0 to n-1) {
      val Array(vh, va) = readLine().split(" ").map(_.toInt)
      h(i) = vh
      a(i) = va
    }

    println((for (x <- h.iterator; y <- a.iterator) yield (x, y)).filter(x => x._1 == x._2).length)
  }
}

object A268 {
  @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 = Array.fill(n)(readInts(2))

    var res = 0
    for(i <- 0 until n) {
      for(j <- 0 until n if i != j) {
        if(input(i)(0) == input(j)(1)) res += 1
      }
    }

    println(res)
  }
}

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

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

  val N = sc.nextInt
  val hs = new Array[Int](N)
  val as = new Array[Int](N)
  for (i <- 0 until N) {
    hs(i) = sc.nextInt
    as(i) = sc.nextInt
  }

  val answer: Int = {
    for {
      h <- hs
      a <- as
      if h == a
    } yield 1
  } sum

  out.println(answer)
  out.close
}

object Games {
	def main (args: Array[String]) {
		val scanner = new java.util.Scanner(System.in);
		val n = scanner.nextInt();
		// Parsing input
		var teams = new Array[(Int,Int)](n);
		for (i <- 0 to n-1) {
		  teams(i) = (scanner.nextInt(), scanner.nextInt());
		}
		// Computation
		var output = 0
		for (i <- 0 to n-1) {
		  for (j <- 0 to n-1) {
		    if (i!=j) {
		      val (home,_) = teams(i)
		      val (_, guest) = teams(j)
		      if (home == guest)
		        output += 1
		    }
		  }
		}
		println(output)
	}
}

object Matchi extends App {
  var ss = (Console.readLine.split(" ")) map (_.toInt)
  val n = ss(0)

  def readMatches(nn:Int):List[(Int,Int)] =
    if (nn == 0) List()
    else {
        val sss = (Console.readLine.split(" ")) map (_.toInt)
        (sss(0), sss(1)) :: readMatches(nn-1)
    }

  def cntMatch(pl:List[(Int,Int)], ac:Int, bc:Int):Int =
  	pl match {
  	case Nil => 0
  	case (a,b) :: tl => ((if (b==ac) 1 else 0) +
  		(if (a==bc) 1 else 0) +
  		cntMatch(tl, ac,bc))
  	}                                         //> cntMatch: (pl: List[(Int, Int)], ac: Int, bc: Int)Int

  def cntSame(pl:List[(Int,Int)]):Int =
  	pl match {
  	case Nil => 0
  	case (a,b) :: tl => cntMatch(tl, a,b) + cntSame(tl)
  	}

  val pl = readMatches(n)
  println(cntSame(pl))
}

object A
{
    def main(args: Array[String])
    {
        val n = readLine().toInt
        val colors=Array.ofDim[Int](n,2)
        for (i <- 0 until n)
        {
            colors(i)=readLine.split(" ").map(_.toInt)
        }
        println((for(x<- colors.iterator; y<-colors.iterator) yield(x,y)).filter(x => x._1(0) == x._2(1)).length)
    }
}

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

object test5 extends App {
    val n=readLine.toInt
    val colors=Array.ofDim[Int](n,2)
    for(i<-0 until n){
        colors(i)=readLine.split(" ").map(_.toInt)
    }

    val list=for(i<-0 until n; j<-0 until n if i!=j) yield
        if(colors(i)(0)==colors(j)(1)) 1 else 0

    println(list.sum)
}

object Main {
  def main(args: Array[String]) {
    val num = readInt()
    var s = List[(Int, Int)]()
    for (i <- 0 until num) {
      val a = readLine().split(" ").map(_.toInt)
      s = (a(0), a(1)) :: s
    }
    val r = s.foldLeft(0) { (acc, t) =>
      acc + s.foldLeft(0) { (acc, tt) => if (t._1 == tt._2) acc + 1 else acc }
    }
    println(r)
  }
}

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 problem extends App {
  val cin = new Scanner(System.in)
  val n = cin.nextInt()
  var cnt = 0
  val t = for(i <- 1 to n) yield (cin.nextInt(), cin.nextInt())
  for(i <-  t) for(j <- t) if(i._1 == j._2) cnt += 1
  println(cnt)
}

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

object Games {

   def readInts() : Array[Int] =
     readLine.split(' ').map(_.toInt)

   def main(args: Array[String]) {
     val n = readInt
     val colors = for {
       i <- 1 to n
       line = readInts
     } yield(line(0),line(1))
     val games =
       for {
         i <- 0 to n-1
         j <- 0 to n-1
         if (i != j)
       } yield (i,j)
     println(games.count(p => colors(p._1)._1 == colors(p._2)._2))
   }

}

import scala.Math.pow;
import scala.collection.mutable.LinkedList

object App {
	def readInts:Array[Int] = (readLine split " ") map (_.toInt)
                                                  //> readInts: => Array[Int]                              //> solve: (n: Int, m: Int, prev: Int, a: Int, b: Int)(Int, Int)

	def f1_io() = {
		val Array(n) = readInts
		val homeColor = new Array[Int](n)
		val outColor = new Array[Int](n)
		for (i <- 1 to n) {
		  val a = readInts
		  homeColor(i - 1) = a(0)
		  outColor(i - 1) = a(1)
		}

		print ((homeColor map (x => (outColor filter (y => x == y)).length)).sum)
	}
  def main(args: Array[String]): Unit = {
	f1_io
  }

}

  object Games extends App {
  	def resolve(): Int = {
  		var hs = Map[Int, Int]()
  		var as = Map[Int, Int]()

  		val lines = io.Source.stdin.getLines.toList.tail

  		for (elem <- lines) {
  			val (homekit: Int, awaykit: Int) = {
  				val tokens = elem.split(" ")
  				(tokens(0).toInt, tokens(1).toInt)
  			}

  			hs = hs + (homekit -> (hs.getOrElse(homekit, 0) + 1))
  			as = as + (awaykit -> (as.getOrElse(awaykit, 0) + 1))
  		}

  		var sum = 0
  		for ((k, v) <- hs) {
  			sum += v * as.getOrElse(k, 0)
  		}

  		sum
  	}

	print(resolve())
  }

object A00268 extends App {
  def parseInt(str: String, count: Int): Seq[Int] = {
    val scanner = new java.util.Scanner(str)
    val res = (1 to count) map (_ => scanner.nextInt())
    scanner.close()
    res
  }
  def scanInts(count: Int): Seq[Int] = parseInt(Console.readLine, count)
  def readMatrix(row: Int, col: Int) = (1 to row) map (x => scanInts(col))

  def oneIntLine = {
    val Seq(count) = parseInt(Console.readLine(), 1);
    count
  }

  def frequency[T](seq: Seq[T]) = seq.groupBy(identity).mapValues(_.size).withDefaultValue(0)

  val nTeams = oneIntLine
  val colors = readMatrix(nTeams, 2)
  val guestColorFreq = frequency(colors.map(_(1)))
  val result = colors.map(x => guestColorFreq(x(0))).sum
  println(result)
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val n = in.next().toInt
  println(in.next().split("WUB").filter(_.nonEmpty).mkString(" "))
}

  object Games extends App {
  	def resolve(): Int = {
  		var hs = Map[Int, Int]()
  		var as = Map[Int, Int]()

  		val lines = io.Source.stdin.getLines.toList.tail

  		for (elem <- lines) {
  			val (homekit: Int, awaykit: Int) = {
  				val tokens = elem.split(" ")
  				(tokens(0).toInt, tokens(1).toInt)
  			}

  			hs = hs + (homekit -> (hs.getOrElse(homekit, 0) + 1))
  			as = as + (awaykit -> (as.getOrElse(awaykit, 0) + 1))
  		}

  		var sum = 0
  		for ((k, v) <- hs) {
  			sum += v * as.getOrElse(k, 0)
  		}

  		sum
  	}
  }


import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val n = scala.io.StdIn.readInt()
    val A:Array[Long] = StdIn.readLine().split(" ").map(_.toLong).sortWith( _ > _)

    print(A.zipWithIndex.foldLeft((0L,0L))({
      case(b,(a,i)) =>
        if(i == 0) {
          (a,a)
        } else {
          val k = math.max(0, math.min(b._2 - 1, a))
          (b._1 + k, k)
        }
    })._1)
  }

}

/**
  * Created by octavian on 06/02/2016.
  */
object MakeClass {

  val INF = 1000000005

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

    //System.setIn(new FileInputStream("./src/makeClass.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/makeClass.out")))

    val N = readInt()
    val vals = readLine().split(" ").map(_.toInt).sorted

    var res: BigInt = 0
    var last = INF
    for(i <- vals.length - 1 to 0 by -1) {
      val toAdd = Math.min(vals(i), last - 1)
      last = toAdd
      if(toAdd > 0) {
        res += toAdd
      }
    }

    println(res)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  var used = Set.empty[Int]
  println(in.next().split(' ').map(_.toInt).zipWithIndex.foldLeft(0l) {
    case (acc, (count, index)) =>
      var nc = count
      while (nc > 0 && used.contains(nc)) nc -= 1
      if (nc != 0) {
        used += nc
      }
      acc + nc
  })
}

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

import scala.annotation.implicitNotFound
import scala.collection.mutable
import scala.reflect.ClassTag

/**
  * Created by nimas on 2/4/16.
  */
object MakingAString extends App{

  class Template(val delim: String = " ") {

    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    val it = Iterator.iterate(new StringTokenizer(""))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))

    def nextTs[T: ParseAble](n: Int)(delim: String = " ")(implicit ev: ClassTag[T]) = (Array fill n) {
      nextT[T](delim)
    }

    def nextT[T: ParseAble](delim: String = " ") = {
      val x = it.find(_.hasMoreTokens)
      implicitly[ParseAble[T]].parse(x get)
    }

    def close(): Unit = {
      in.close()
      out.close()
    }

    @implicitNotFound("No member of type class ParseAble in scope for ${T}")
    trait ParseAble[T] {
      def parse(strTok: StringTokenizer): T
    }

    object ParseAble {

      implicit object ParseAbleInt extends ParseAble[Int] {
        override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt
      }

      implicit object ParseAbleLong extends ParseAble[Long] {
        override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong
      }

      implicit object ParseAbleDouble extends ParseAble[Double] {
        override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble
      }

      implicit object ParseAbleBigInt extends ParseAble[BigInt] {
        override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())
      }

    }

  }

  val io = new Template()

  import io._

  val n = nextT[Int]()
  val a = nextTs[Long](n)() sorted Ordering.Long

  val map = new mutable.HashMap[Long, Boolean]()

  out.println((a.iterator map {
    x => {
      if (map getOrElse(x, true)) {
        map put(x, false)
        x
      } else {
        val find = x - 1 to(1, -1) find {
          !map.contains(_)
        } getOrElse 0l
        if (find != 0) map put(find, false)
        find
      }
    }
  }).sum)

  close()

}

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

object _624B extends CodeForcesApp {
  override type Result = Long

  override def solve(read: Scanner) = {
    val n = read[Int]
    val seen = mutable.Set.empty[Long]
    @tailrec def add(i: Long): Unit = if (seen(i)) add(i-1) else if (i > 0) {val _ = seen += i}
    repeat(n)(add(read[Long]))
    seen.sum
  }

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

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class Scanner(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

  private[this] val tokenizers = Iterator.continually(reader.readLine()).takeWhile(_ != null)
                                         .map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(next())

  def nextLine(): String = tokenizer().get.nextToken("\n\r")
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

trait Parser[A] {
  def apply(s: String): A
}
object Parser {
  def apply[A](f: String => A) = new Parser[A] {
    override def apply(s: String) = f(s)
  }
  implicit val tokenString: Parser[String] = Parser(identity)
  implicit val tokenChar: Parser[Char] = Parser(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val tokenBool: Parser[Boolean] = Parser(_.toBoolean)
  implicit val tokenInt: Parser[Int] = Parser(_.toInt)
  implicit val tokenLong: Parser[Long] = Parser(_.toLong)
  implicit val tokenBigInt: Parser[BigInt] = Parser(BigInt(_))
  implicit val tokenDouble: Parser[Double] = Parser(_.toDouble)
  implicit val tokenBigDecimal: Parser[BigDecimal] = Parser(BigDecimal(_))
}

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

object _624B extends CodeForcesApp {
  override type Result = Long

  override def solve(read: InputReader) = {
    val n = read[Int]
    val seen = mutable.Set.empty[Long]
    @tailrec def add(i: Long): Unit = if (seen(i)) add(i-1) else if (i > 0) {val _ = seen += i}
    repeat(n)(add(read[Long]))
    seen.sum
  }

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

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(this)

  def apply[C[_], A: Parser](n: Int)(implicit cbf: Parser.Collection[C, A]): C[A] = {
    val builder = cbf()
    for {i <- 1 to n} builder += apply[A]
    builder.result()
  }

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

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

trait Parser[A] {
  def apply(reader: InputReader): A
}
object Parser {
  def apply[A](f: String => A) = new Parser[A] {
    override def apply(reader: InputReader) = f(reader.next())
  }
  type Collection[C[_], A] = scala.collection.generic.CanBuildFrom[C[A], A, C[A]]
  implicit def collectionParser[C[_], A: Parser](implicit cbf: Collection[C, A]): Parser[C[A]] = new Parser[C[A]] {
    override def apply(reader: InputReader) = reader[C, A](reader[Int])
  }
  implicit val stringParser: Parser[String] = Parser(identity)
  implicit val charParser: Parser[Char] = Parser(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val booleanParser: Parser[Boolean] = Parser(_.toBoolean)
  implicit val intParser: Parser[Int] = Parser(_.toInt)
  implicit val longParser: Parser[Long] = Parser(_.toLong)
  implicit val bigIntParser: Parser[BigInt] = Parser(BigInt(_))
  implicit val doubleParser: Parser[Double] = Parser(_.toDouble)
  implicit val bigDecimalParser: Parser[BigDecimal] = Parser(BigDecimal(_))
}

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

object _624B extends CodeForcesApp {
  override type Result = Long

  override def solve(read: InputReader) = {
    val n = read[Int]
    val seen = mutable.Set.empty[Long]
    @tailrec def add(i: Long): Unit = if (seen(i)) add(i-1) else if (i > 0) {val _ = seen += i}
    repeat(n)(add(read[Long]))
    seen.sum
  }

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

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  type Result
  def solve(scanner: InputReader): Result
  def format(result: Result): String
  def apply(scanner: InputReader): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new InputReader(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io.{BufferedReader, Reader, InputStreamReader, StringReader, InputStream}
import java.util.StringTokenizer

class InputReader(reader: BufferedReader) extends Iterator[String] with AutoCloseable {
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream) = this(new InputStreamReader(inputStream))
  def this(str: String) = this(new StringReader(str))

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

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

  def apply[A: Parser]: A = implicitly[Parser[A]].apply(next())

  def tillEndOfLine(): String = tokenizer().get.nextToken("\n\r")
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

trait Parser[A] {
  def apply(s: String): A
}
object Parser {
  def apply[A](f: String => A) = new Parser[A] {
    override def apply(s: String) = f(s)
  }
  implicit val stringParser: Parser[String] = Parser(identity)
  implicit val charParser: Parser[Char] = Parser(s => s.ensuring(_.length == 1, s"Expected Char; found $s").head)
  implicit val booleanParser: Parser[Boolean] = Parser(_.toBoolean)
  implicit val intParser: Parser[Int] = Parser(_.toInt)
  implicit val longParser: Parser[Long] = Parser(_.toLong)
  implicit val bigIntParser: Parser[BigInt] = Parser(BigInt(_))
  implicit val doubleParser: Parser[Double] = Parser(_.toDouble)
  implicit val bigDecimalParser: Parser[BigDecimal] = Parser(BigDecimal(_))
}

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

object _624B extends CodeForcesApp {
  override type Result = Long

  override def solve(scanner: Scanner) = {
    import scanner._
    val seen = mutable.Set.empty[Long]
    @tailrec def add(i: Long): Unit = if (seen(i)) add(i-1) else if (i > 0) seen += i
    repeat(nextInt())(add(nextLong()))
    seen.sum
  }

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

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

/**
  * Created by Andrew Tsibin https://github.com/Evilnef.
  */
object Problemset624 {
  def main(args: Array[String]): Unit = {
    val problem = new ProblemB
    problem.solve()
  }

  private abstract class Problem {
    def solve()
  }

  private class ProblemA extends Problem {
    override def solve(): Unit = {
      val Array(d, l, v1, v2) = scala.io.StdIn.readLine().split(" ").map(_.toDouble)
      val result = (l - d) / (v1 + v2)
      println(result)
    }
  }

  private class ProblemB extends Problem {
    override def solve(): Unit = {
      var maxStringLengths: BigInt = 0
      val n = scala.io.StdIn.readInt()
      val a = scala.io.StdIn.readLine().split(" ").map(BigInt(_)).sortWith(_ > _)
      for (i <- a.indices) {
        if (i == 0) maxStringLengths += a(i)
        else maxStringLengths += {
          if (a(i) >= a(i - 1))
            a(i) = a(i - 1) - 1
          if (a(i) < 0) 0 else a(i)
        }
      }
      println(maxStringLengths)
    }
  }

}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val n = scala.io.StdIn.readInt()
    val A:Array[Long] = StdIn.readLine().split(" ").map(_.toLong)
    Sorting.quickSort(A)

    print(A.reverse.zipWithIndex.foldLeft((0L,0L))({
      case(b,(a,i)) =>
        if(i == 0) {
          (a,a)
        } else {
          val k = math.max(0, math.min(b._2 - 1, a))
          (b._1 + k, k)
        }
    })._1)
  }

}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val n = scala.io.StdIn.readInt()
    val A:Array[Long] = StdIn.readLine().split(" ").map(_.toLong)
    Sorting.quickSort(A)

    var acc:Long = 0
    A.reverse.zipWithIndex.foldLeft(0L)({
      case(b,(a,i)) =>
        if(i == 0) {
          acc+=a
          a
        } else {
          acc += math.max(math.min(b - 1, a),0)
          math.max(math.min(b - 1, a),0)
        }
    })

    print(acc)

  }

}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val n = scala.io.StdIn.readInt()
    val A:Array[Long] = StdIn.readLine().split(" ").map(_.toLong).sorted.reverse

    print(A.zipWithIndex.foldLeft((0L,0L))({
      case(b,(a,i)) =>
        if(i == 0) {
          (a,a)
        } else {
          val k = math.max(0, math.min(b._2 - 1, a))
          (b._1 + k, k)
        }
    })._1)
  }

}

/**
  * Created by octavian on 06/02/2016.
  */
object MakeClass {

  val INF = 1000000005

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

    //System.setIn(new FileInputStream("./src/makeClass.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/makeClass.out")))

    val N = readInt()
    var vals = readLine().split(" ").map(_.toInt)

    var res = 0
    var last = INF
    for(i <- vals.length - 1 to 0 by -1) {
      val toAdd = Math.min(vals(i), last - 1)
      last = toAdd
      if(toAdd > 0) {
        res += toAdd
      }
    }

    println(res)

  }

}

/**
  * Created by octavian on 06/02/2016.
  */
object MakeClass {

  val INF = 1000000005

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

    //System.setIn(new FileInputStream("./src/makeClass.in"))
    //System.setOut(new PrintStream(new FileOutputStream("./src/makeClass.out")))

    val N = readInt()
    val vals = readLine().split(" ").map(_.toInt).sorted

    var res = 0
    var last = INF
    for(i <- vals.length - 1 to 0 by -1) {
      val toAdd = Math.min(vals(i), last - 1)
      last = toAdd
      if(toAdd > 0) {
        res += toAdd
      }
    }

    println(res)

  }

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val arr = Array.ofDim[Int](26)
  var used = Set.empty[Int]
  in.next().split(' ').map(_.toInt).zipWithIndex.foreach {
    case (count, index) =>
      var nc = count
      while (nc > 0 && used.contains(nc)) nc -= 1
      if (nc != 0) {
        arr(index) = nc
        used += nc
      }
  }
  println(arr.sum)

}

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

import scala.annotation.implicitNotFound
import scala.collection.mutable
import scala.reflect.ClassTag

/**
  * Created by nimas on 2/4/16.
  */
object MakingAString extends App{

  class Template(val delim: String = " ") {

    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    val it = Iterator.iterate(new StringTokenizer(""))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))

    def nextTs[T: ParseAble](n: Int)(delim: String = " ")(implicit ev: ClassTag[T]) = (Array fill n) {
      nextT[T](delim)
    }

    def nextT[T: ParseAble](delim: String = " ") = {
      val x = it.find(_.hasMoreTokens)
      implicitly[ParseAble[T]].parse(x get)
    }

    def close(): Unit = {
      in.close()
      out.close()
    }

    @implicitNotFound("No member of type class ParseAble in scope for ${T}")
    trait ParseAble[T] {
      def parse(strTok: StringTokenizer): T
    }

    object ParseAble {

      implicit object ParseAbleInt extends ParseAble[Int] {
        override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt
      }

      implicit object ParseAbleLong extends ParseAble[Long] {
        override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong
      }

      implicit object ParseAbleDouble extends ParseAble[Double] {
        override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble
      }

      implicit object ParseAbleBigInt extends ParseAble[BigInt] {
        override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())
      }

    }

  }

  val io = new Template()

  import io._

  val n = nextT[Int]()
  val a = nextTs[Int](n)() sorted Ordering.Int

  val map = new mutable.HashMap[Int, Boolean]()

  out.println((a.iterator map {
    x => {
      if (map getOrElse(x, true)) {
        map put(x, false)
        x
      } else {
        x - 1 to(1, -1) find {
          !map.contains(_)
        } getOrElse 0
      }
    }
  }).sum)

  close()

}

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

import scala.annotation.implicitNotFound
import scala.collection.mutable
import scala.reflect.ClassTag

/**
  * Created by nimas on 2/4/16.
  */
object MakingAString extends App{

  class Template(val delim: String = " ") {

    val in = new BufferedReader(new InputStreamReader(System.in))
    val out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)))
    val it = Iterator.iterate(new StringTokenizer(""))(tok => if (tok.hasMoreTokens) tok else new StringTokenizer(in.readLine(), delim))

    def nextTs[T: ParseAble](n: Int)(delim: String = " ")(implicit ev: ClassTag[T]) = (Array fill n) {
      nextT[T](delim)
    }

    def nextT[T: ParseAble](delim: String = " ") = {
      val x = it.find(_.hasMoreTokens)
      implicitly[ParseAble[T]].parse(x get)
    }

    def close(): Unit = {
      in.close()
      out.close()
    }

    @implicitNotFound("No member of type class ParseAble in scope for ${T}")
    trait ParseAble[T] {
      def parse(strTok: StringTokenizer): T
    }

    object ParseAble {

      implicit object ParseAbleInt extends ParseAble[Int] {
        override def parse(strTok: StringTokenizer): Int = strTok nextToken() toInt
      }

      implicit object ParseAbleLong extends ParseAble[Long] {
        override def parse(strTok: StringTokenizer): Long = strTok nextToken() toLong
      }

      implicit object ParseAbleDouble extends ParseAble[Double] {
        override def parse(strTok: StringTokenizer): Double = strTok nextToken() toDouble
      }

      implicit object ParseAbleBigInt extends ParseAble[BigInt] {
        override def parse(strTok: StringTokenizer): BigInt = BigInt(strTok nextToken())
      }

    }

  }

  val io = new Template()

  import io._

  val n = nextT[Int]()
  val a = nextTs[Int](n)() sorted Ordering.Int

  val map = new mutable.HashMap[Int, Boolean]()

  out.println((a.iterator map {
    x => {
      if (map getOrElse(x, true)) {
        map put(x, false)
        x
      } else {
        val find = x - 1 to(1, -1) find {
          !map.contains(_)
        } getOrElse 0
        if (find != 0) map put(find, false)
        find
      }
    }
  }).sum)

  close()

}

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

object _624B extends CodeForcesApp {
  override type Result = Int

  override def solve(scanner: Scanner) = {
    import scanner._
    val n = nextInt()
    val seen = mutable.Set.empty[Int]
    @tailrec def add(i: Int): Unit = if (seen(i)) add(i-1) else if (i > 0) seen += i
    repeat(n)(add(nextInt()))
    seen.sum
  }

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

  override def format(result: Result) = result.toString
}
/****************************[Ignore Template Below]****************************************/
abstract class CodeForcesApp {
  val isOnlineJudge: Boolean = sys.props.get("ONLINE_JUDGE").exists(_.toBoolean)
  def debug(x: Any): Unit = if (!isOnlineJudge) println(x)
  val mod: Int = 1000000007
  type Result
  def solve(scanner: Scanner): Result
  def format(result: Result): String
  def apply(scanner: Scanner): String = format(solve(scanner))
  def main(args: Array[String]): Unit = println(apply(new Scanner(System.in)))
}
/*********************************[Scala Scanner]*******************************************/
import java.io._
import java.nio.file.{Files, Path}
import java.util.StringTokenizer

import scala.io.Codec

/**
 * Scala implementation of a faster java.util.Scanner
 * See: http://codeforces.com/blog/entry/21125
 * All next methods throw NoSuchElementException when !hasNext
 */
class Scanner(reader: LineNumberReader) extends Iterator[String] with AutoCloseable {
  def this(reader: BufferedReader) = this(new LineNumberReader(reader))
  def this(reader: Reader) = this(new BufferedReader(reader))
  def this(inputStream: InputStream)(implicit codec: Codec) = this(new InputStreamReader(inputStream, codec.charSet))
  def this(path: Path)(implicit codec: Codec) = this(Files.newBufferedReader(path, codec.charSet))
  def this(file: File)(implicit codec: Codec) = this(file.toPath)(codec)
  def this(str: String) = this(new StringReader(str))

  val lines = Iterator.continually(reader.readLine()).takeWhile(_ != null)

  private[this] val tokenizers = lines.map(new StringTokenizer(_)).filter(_.hasMoreTokens)
  private[this] var current: Option[StringTokenizer] = None

  @inline private[this] def tokenizer(): Option[StringTokenizer] = current.find(_.hasMoreTokens) orElse {
    current = if (tokenizers.hasNext) Some(tokenizers.next()) else None
    current
  }

  /**
   * Unlike Java's scanner which returns till end of current line, this actually returns the next line
   * @see line() if you want the Java behaviour
   */
  def nextLine(): String = {
    current = None   // reset
    lines.next()
  }
  def lineNumber: Int = reader.getLineNumber
  def line(): String = tokenizer().get.nextToken("\n\r")
  def nextString(): String = next()
  def nextChar(): Char = next().ensuring(_.length == 1).head
  def nextBoolean(): Boolean = next().toBoolean
  def nextByte(radix: Int = 10): Byte = java.lang.Byte.parseByte(next(), radix)
  def nextShort(radix: Int = 10): Short = java.lang.Short.parseShort(next(), radix)
  def nextInt(radix: Int = 10): Int = java.lang.Integer.parseInt(next(), radix)
  def nextLong(radix: Int = 10): Long = java.lang.Long.parseLong(next(), radix)
  def nextBigInt(radix: Int = 10): BigInt = BigInt(next(), radix)
  def nextFloat(): Float = next().toFloat
  def nextDouble(): Double = next().toDouble
  def nextBigDecimal(): BigDecimal = BigDecimal(next())
  override def next() = tokenizer().get.nextToken()
  override def hasNext = tokenizer().nonEmpty
  override def close() = reader.close()
}

/**
  * Created by Andrew Tsibin https://github.com/Evilnef.
  */
object Problemset624 {
  def main(args: Array[String]): Unit = {
    val problem = new ProblemB
    problem.solve()
  }

  private abstract class Problem {
    def solve()
  }

  private class ProblemA extends Problem {
    override def solve(): Unit = {
      val Array(d, l, v1, v2) = scala.io.StdIn.readLine().split(" ").map(_.toDouble)
      val result = (l - d) / (v1 + v2)
      println(result)
    }
  }

  private class ProblemB extends Problem {
    override def solve(): Unit = {
      var maxStringLengths = 0
      val n = scala.io.StdIn.readInt()
      val a = scala.io.StdIn.readLine().split(" ").map(_.toInt).sortWith(_ > _)
      for (i <- a.indices) {
        if (i == 0) maxStringLengths += a(i)
        else maxStringLengths += {
          if (a(i) >= a(i - 1))
            a(i) = a(i - 1) - 1
          if (a(i) < 0) 0 else a(i)
        }
      }
      println(maxStringLengths)
    }
  }

}

import scala.util.Sorting
import scala.io.StdIn
object App {
  def main(args: Array[String]) {

    val n = scala.io.StdIn.readInt()
    val A:Array[Int] = StdIn.readLine().split(" ").map(_.toInt)
    Sorting.quickSort(A)

    var acc = 0
    A.reverse.zipWithIndex.foldLeft(0)({
      case(b,(a,i)) =>
        if(i == 0) {
          acc+=a
          a
        } else {
          acc += math.max(math.min(b - 1, a),0)
          math.max(math.min(b - 1, a),0)
        }
    })

    print(acc)

  }

}


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

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

    // ">"  →  1000,
    // "<"  →  1001,
    // "+"  →  1010,
    // "-"  →  1011,
    // "."  →  1100,
    // ","  →  1101,
    // "["  →  1110,
    // "]"  →  1111.

  val M = Map('>' -> 8,
              '<' -> 9,
              '+' -> 10,
              '-' -> 11,
              '.' -> 12,
              ',' -> 13,
              '[' -> 14,
              ']' -> 15)

  val P = 1000003

  def solve(): Int = {
    val BF = sc.nextLine

    BF.foldLeft(0) { (b, a) =>
      ((b << 4) | M(a)) % P
    }
  }

  out.println(solve)
  out.close
}

object Main {
    def main(args : Array[String]) =
        println (readLine.foldLeft (0) (
            (ans, x) => ((ans << 4) | (("><+-.,[]" indexOf x) + 8)) % 1000003
        ))
}

object Main {
  def main(args: Array[String]) {
    val s = readLine()
    val tr = s.map{
      case '>' => 8
      case '<' => 9
      case '+' => 10
      case '-' => 11
      case '.' => 12
      case ',' => 13
      case '[' => 14
      case ']' => 15
    }
    println(tr.foldLeft(0){ (acc, i) => (acc * 16 + i) % 1000003} )
  }
}

object Solution extends App {
  val in = scala.io.Source.stdin.getLines()
  val str = in.next()

  val map = Map(
    '>' -> 8,
    '<' -> 9,
    '+' -> 10,
    '-' -> 11,
    '.' -> 12,
    ',' -> 13,
    '[' -> 14,
    ']' -> 15)

  println(str.foldLeft(0l) {
    case (acc, ch) => Math.abs(acc << 4) + map(ch)
  } % 1000003)

}


object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  var Array(t, s, q) = in.next().split(" ").map(_.toInt)
  var count = 0
  while (s < t) {
    s *= q
    count += 1
  }
  println(count)

}

object A569 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    var Array(t, s, q) = readInts(3)
    var res = 0
    while(s < t) {
      s *= q
      res += 1
    }
    out.println(res)
    out.close()
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
    //    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream("src/input")))
    val out = new java.io.PrintWriter(System.out)

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.StdIn._

object A extends App {
  val Array(t, s, q) = readLine().split(" ").map(_.toInt)

  var played = 0
  var started = 1
  var current = 0

  while (s + (current * ((q - 1.0) / q)) < t) {
    if (played + 1 <= s + ((current + 1) * ((q - 1.0) / q))) {
      played += 1
    } else {
      played = 1
      started += 1
    }

    current += 1
  }

  println(started)
}

import java.util.Scanner

object PA extends App {
    var in = new Scanner(System.in)
    val Vector(t, s, q) = (1 to 3).map(_ => in.nextInt())
    def sol(ns:Int):Int = if(ns >= t) 0 else sol(ns*q) + 1
    println(sol(s).toString)
}

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

import scala.collection.mutable

object A {

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

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

  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 java.lang.Long.parseLong(next)

  def nextDouble: Double = return java.lang.Double.parseDouble(next)

  class MultiHashSet[T <% Comparable[T]] {
    val map = new mutable.HashMap[T, Int]()

    def count(x: T): Int = {
      return map.getOrElse(x, 0)
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  class MultiTreeSet[T <% Comparable[T]] {
    val map = new TreeMap[T, Int]()

    def count(x: T): Int = {
      val res = map.get(x)
      if (res == null)
        return 0
      return res
    }

    def add(x: T): Unit = map.put(x, count(x) + 1)

    def first(): T = return map.firstKey()

    def last(): T = return map.lastKey()

    def remove(x: T): Boolean = {
      val prev = count(x)
      if (prev == 0)
        return false
      if (prev == 1) {
        map.remove(x)
      } else {
        map.put(x, prev - 1)
      }
      return true
    }
  }

  /**
   * Segment tree for any commutative function
   * @param values Array of Int
   * @param commutative function like min, max, sum
   * @param zero zero value - e.g. 0 for sum, Inf for min, max
   */
  class SegmentTree(values: Array[Int])(commutative: (Int, Int) => Int)(zero: Int) {
    private val SIZE = 1e5.toInt
    private val n = values.length
    val t = new Array[Int](2 * n)
    Array.copy(values, 0, t, n, n)

    // build segment tree
    def build = {
      for (i <- n - 1 until 0 by -1) {
        t(i) = commutative(t(2 * i), t(2 * i + 1))
      }
    }

    // change value at position p to x
    // TODO beatify
    def modify(p: Int, x: Int) = {
      var pos = p + n
      t(pos) = x
      while (pos > 1) {
        t(pos / 2) = commutative(t(pos), t(pos ^ 1))
        pos /= 2
      }
    }

    // TODO implement me!
    def modify(p: Int, left: Int, right: Int) = ???

    def query(p: Int) = ???

    // sum [l, r)
    // min l = 0
    // max r = n
    // TODO beatify
    def query(left: Int, right: Int): Int = {
      var res = zero
      var r = right + n
      var l = left + n
      while (l < r) {
        if (l % 2 == 1) {
          res = commutative(res, t(l))
          l += 1
        }
        if (r % 2 == 1) {
          r -= 1
          res = commutative(res, t(r))
        }
        l /= 2
        r /= 2
      }
      res
    }
  }

  def solve: Int = {
    val t = nextInt
    var s = nextInt
    val q = nextInt
    var count = 0
    while (s < t) {
      s *= q
      count += 1
    }
    out.println(count)
    return 0
  }
}

import scala.io.StdIn._

object A extends App {
  val Array(t, s, q) = readLine().split(" ").map(_.toInt)

  var downloaded = s.toDouble
  var played = 0
  var started = 1

  var speed = (q - 1.0) / q

  while (downloaded < t) {
    downloaded += speed

    if (played + 1 <= downloaded) {
      played += 1
    } else {
      played = 0
      started += 1
    }
  }

  println(started)
}

import scala.io.StdIn._

object A extends App {
  val Array(t, s, q) = readLine().split(" ").map(_.toInt)

  var downloaded = s.toDouble
  var played = 0
  var started = 1

  var speed = (q - 1.0) / q

  while (downloaded < t) {
    downloaded += speed

    if (played + 1 <= downloaded) {
      played += 1
    } else {
      played = 1
      started += 1
    }
  }

  println(started)
}

import scala.io.StdIn._

object A extends App {
  val Array(t, s, q) = readLine().split(" ").map(_.toInt)

  var downloaded = s.toDouble
  var played = 0
  var started = 1

  var speed = (q - 1.0) / q

  downloaded += speed

  while (downloaded < t) {

    if (played + 1 <= downloaded) {
      played += 1
    } else {
      played = 1
      started += 1
    }

    downloaded += speed
  }

  println(started)
}

import scala.io.StdIn._

object A extends App {
  val Array(t, s, q) = readLine().split(" ").map(_.toInt)

  var downloaded = s.toDouble
  var played = 0
  var started = 1

  var speed = (q - 1.0) / q

  downloaded += speed

  while (downloaded < t) {

    if (played + 1 <= downloaded) {
      played += 1
    } else {
      played = 0
      started += 1
    }

    downloaded += speed
  }

  println(started)
}

import scala.io.StdIn._

object A extends App {
  val Array(t, s, q) = readLine().split(" ").map(_.toInt)

  var downloaded = s.toDouble
  var played = 0
  var started = 1

  var speed = (q - 1.0) / q

  while (downloaded < t) {
    downloaded += speed

    if (downloaded < t && played + 1 <= downloaded) {
      played += 1
    } else if (downloaded < t) {
      played = 0
      started += 1
    }
  }

  println(started)
}

object Solution extends App{
  val in = scala.io.Source.stdin.getLines()
  val Array(t, s, q) = in.next().split(" ").map(_.toInt)
  var downloaded = 2 * s * (q - 1)
  var count = 1
  while (downloaded < t) {
    downloaded += downloaded * (q - 1)
    count += 1
  }
  println(count)

}


object Main {
  def main(args: Array[String]) {
    val Array(n, r1, r0) = readLine().split(" ").map(_.toInt)
    if (n == 1 && r1 >= r0) println("YES")
    else if (r1 > r0) {
      val angle = math.Pi / n
      if (r0.toDouble / (r1 - r0).toDouble - math.sin(angle) <= 0.000000001) println("YES")
      else (println("NO"))
    } else println("NO")
  }
}

object P140A extends App {

  val Array(n, bigR, r) = readLine.split(" ").map(_.toInt)

  def findSide(angle: Double, a: Double) = a / math.sin(math.toRadians(angle))

  val condition = if (n < 3) bigR >= n * r else math.abs(findSide(180.0 / n, r)) + r <= bigR

  print(if (condition) "YES" else "NO")

}

object main {

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

        val tokens = (readLine()) split " " map Integer.parseInt
        val n = tokens apply 0
        val R = tokens apply 1
        val r = tokens apply 2
        if (n == 1) {if (R >= r) println ("YES") else println("NO")}
        else if ((R-r)*math.sin(math.Pi/n)>=r-0.00000001) println ("YES") else println("NO")
    }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / a + 1E-7).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / (a-(1E-7))).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / (a-0.001)).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / a).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / a + Math.EPS_DOUBLE).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / (a-(Math.EPS_DOUBLE))).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))
      val fit = Math.floor(2 * Math.Pi / (a+(Math.EPS_DOUBLE))).toInt / 2

      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

import scala.io.Source
object A {

  def main(arg: Array[String]) = {
    val in = Source.stdin.getLine(0).split(" ").map(_.toInt)
    val n = in(0)
    val R = in(1).toDouble
    val r = in(2).toDouble

    if (n == 1) {
      if (r <= R)
        println("YES")
      else
        println("NO")
    } else if (r*2.0 > R)
      println("NO")
    else {
      val a = Math.asin(r / (R - r))

      println (a)
      val fit = Math.floor(2 * Math.Pi / a + Math.EPS_DOUBLE).toInt / 2

      println (fit)
      if (n <= fit)
        println("YES")
      else
        println("NO")
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, r1, r0) = readLine().split(" ").map(_.toInt)
    if (n == 1 && r1 >= r0) println("YES")
    else if (r1 > r0) {
      val angle = math.Pi / n
      if (r0.toDouble / (r1 - r0).toDouble <= math.sin(angle)) println("YES")
      else (println("NO"))
    } else println("NO")
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, r1, r0) = readLine().split(" ").map(_.toInt)
    if (n == 1 && r1 >= r0) println("YES")
    else if (r1 > r0) {
      val angle = math.Pi / n
      if (r0.toDouble / (r1 - r0).toDouble - math.sin(angle) <= 0.0000001) println("YES")
      else (println("NO"))
    } else println("NO")
  }
}

object Main {
  def main(args: Array[String]) {
    val Array(n, r1, r0) = readLine().split(" ").map(_.toInt)
    if (n == 1 && r1 >= r0) println("YES")
    else if (r1 > r0) {
      val angle = math.Pi / n
      if (r0.toDouble / (r1 - r0).toDouble - math.sin(angle) <= 0.001) println("YES")
      else (println("NO"))
    } else println("NO")
  }
}


import scala.collection._

object A extends App {

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

  val n = readInt
  val xs = readInts(n)

  for (i <- 1 until n) {
    val l1 = math.min(xs(i - 1), xs(i))
    val r1 = math.max(xs(i - 1), xs(i))
    for (j <- 1 until n) {
      val l2 = math.min(xs(j - 1), xs(j))
      val r2 = math.max(xs(j - 1), xs(j))
      if ((l1 < l2 && r1 > l2 && r1 < r2) || (r1 > r2 && l1 > l2 && l1 < r2) ||
          (l2 < l1 && r2 > l1 && r2 < r1) || (r2 > r1 && l2 > l1 && l2 < r1)) {
        println("yes")
        //println(i, j)
        exit
      }
    }
  }

  println("no")
}

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

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

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

  var flag = false
  breakable {
    for (i <- 0 until N - 2; j <- (i + 2) until N - 1) {
      val a = P(i)
      val b = P(i + 1)
      val c = P(j)
      val d = P(j + 1)
      if ((c - a).signum * (c - b).signum * (d - a).signum * (d - b).signum < 0) {
        flag = true
        break
      }
    }
  }

  val res = if (flag) "yes" else "no"

  out.println(res)
  out.close
}

import java.util.Scanner
import scala.collection.mutable.ArrayBuffer

object Solver extends App {
  val cin = new Scanner(System.in)

  val n = cin.nextInt
  cin.nextLine
  val points = cin.nextLine.split(" ").map(_.toInt).toSeq

  val connections = for (i <- 0 until n - 1) yield (points(i), points(i + 1))

  var intersection = "no"
  connections.foreach { case (a, d) =>
    val p1 = Seq(a, d)
    val A = p1.min
    val D = p1.max

    connections.foreach { case (b, c) =>
      val p2 = Seq(b, c)
      val B = p2.min
      val C = p2.max

      if (B < D && D < C && A < B)
        intersection = "yes"
    }
  }

  println(intersection)
}

object Main {
  def main(args: Array[String]) {
    val n=readLine().toInt
    val a=readLine().split(" ").map(_ toInt)
    val b=(0 until n-1).map(i=>(math.min(a(i),a(i+1)),math.max(a(i),a(i+1))))
    println(  if (b.exists(e1=>b.exists(e2=>(e1._1<e2._1 && e2._1<e1._2 && e1._2<e2._2)
     || (e2._1<e1._1 && e1._1<e2._2 && e2._2<e1._2))))
        "yes"
    else "no")
  }
}

object Solution358A extends App {

  def solution() {
    val n = _int
    val coords = 1.to(n).map(_ => _int)
    val intervals = coords.zip(coords.tail)

    def norm(a: (Int, Int)): (Int, Int) = (scala.math.min(a._1, a._2), scala.math.max(a._1, a._2))

    def inside(a: (Int, Int), x: Int): Boolean = a._1 < x && x < a._2
    def oneInside(a: (Int, Int), b: (Int, Int)): Boolean = inside(a, b._1) ^ inside(a, b._2)

    def intersects(a: (Int,Int), b: (Int, Int)): Boolean = {
      val x = norm(a)
      val y = norm(b)
      val res = oneInside(x, y) && oneInside(y, x)
      if (res) {
        //println(a)
        //println(b)
      }
      res
    }

    val hasInt = intervals.find(a => {
      intervals.find(b => intersects(a, b)).isDefined
    }).isDefined

    if (hasInt) {
      println("yes")
    } else {
      println("no")
    }
  }

  //////////////////////////////////////////////////
  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.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).sliding(2).toList
  val r = data.forall{i => data.forall { j =>
    val minFirst = Math.min(i.head, i.last)
    val maxFirst = Math.max(i.head, i.last)
    val minSecond = Math.min(j.head, j.last)
    val maxSecond = Math.max(j.head, j.last)
    if (i == j)
      true
    else {
      val r = maxFirst <= minSecond || minFirst >= maxSecond || (maxFirst <= maxSecond && minFirst >= minSecond) ||
        (maxSecond <= maxFirst && minSecond >= minFirst)
      r
    }}}
  if (!r)
    println("yes")
  else
    println("no")
}

object A358 {

  import IO._
  import collection.{mutable => cu}

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val in = readInts(n)
    val x = cu.ArrayBuffer.empty[(Int, Int)]
    for(i <- 1 until n)
      x.append((math.min(in(i-1), in(i)), math.max(in(i-1), in(i))))
    val res = x.sorted
    var break = false
    for(i <- res.indices; j <- res.indices if i!=j && !break) {
      if(res(i)._1 < res(j)._1 && res(i)._2 > res(j)._1 && res(j)._2 > res(i)._2) {
        println("yes")
        break = true
      }
    }
    if(!break){
      println("no")
    }
  }

  object IO {
    private val input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))

    @inline def read: String = input.readLine()

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

    def readInt: Int = tokenizeLine.nextToken.toInt

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

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

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

}

import scala.io.Source

object Solution extends App {
  val in = Source.stdin.getLines()
  val n = in.next().toInt
  val data = in.next().split(' ').map(_.toInt).sliding(2)
  val r = data.forall{i => data.forall { j =>
    val minFirst = Math.min(i.head, i.last)
    val maxFirst = Math.max(i.head, i.last)
    val minSecond = Math.min(j.head, j.last)
    val maxSecond = Math.max(j.head, j.last)
    if (i == j)
      true
    else {
      maxFirst <= minSecond || minFirst >= maxSecond || (maxFirst <= maxSecond && minFirst >= minSecond) ||
        (maxSecond <= maxFirst && minSecond >= minFirst)
    }}}
  if (!r)
    println("yes")
  else
    println("no")
}

import scala.collection._

object A extends App {

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

  val n = readInt
  val xs = readInts(n)

  for (i <- 1 until n) {
    val l1 = xs(i - 1)
    val r1 = xs(i)
    for (j <- 1 until n) {
      val l2 = xs(j - 1)
      val r2 = xs(j)
      if ((l1 < l2 && r1 > l2 && r1 < r2) || (r1 > r2 && l1 > l2 && l1 < r2) ||
          (l2 < l1 && r2 > l1 && r2 < r1) || (r2 > r1 && l2 > l1 && l2 < r1)) {
        println("yes")
        //println(i, j)
        exit
      }
    }
  }

  println("no")
}

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

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

  val N = sc.nextInt
  val ps = List.fill(N / 2, 2)(sc.nextInt)
  val res = if (ps(0) == ps(0).sorted && ps(1) == ps(1).sorted.reverse) "no"
            else "yes"

  out.println(res)
  out.close
}

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

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

  val N = sc.nextInt
  val P = Array.fill(N)(sc.nextLong)

  var flag = false
  breakable {
    for (i <- 0 until N - 2; j <- (i + 1) until N - 1) {
      val a = P(i)
      val b = P(i + 1)
      val c = P(j)
      val d = P(j + 1)
      if ((c - a) * (c - b) * (d - a) * (d - b) < 0) {
        flag = true
        break
      }
    }
  }

  val res = if (flag) "YES" else "NO"

  out.println(res)
  out.close
}

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

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

  val N = sc.nextInt
  val P = Array.fill(N)(sc.nextLong)

  var flag = false
  breakable {
    for (i <- 0 until N - 2; j <- (i + 1) until N - 1) {
      val a = P(i)
      val b = P(i + 1)
      val c = P(j)
      val d = P(j + 1)
      if ((c - a) * (c - b) * (d - a) * (d - b) < 0) {
        flag = true
        break
      }
    }
  }

  val res = if (flag) "yes" else "no"

  out.println(res)
  out.close
}

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

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

  val N = sc.nextInt
  val ps = List.fill(N / 2, 2)(sc.nextInt).transpose
  val res = if (ps(0) == ps(0).sorted && ps(1) == ps(1).sorted.reverse) "no"
            else "yes"

  out.println(res)
  out.close
}


object A672 {

  import IO._

  def main(args: Array[String]): Unit = {
    val Array(n) = readInts(1)
    val ret = (1 to 500).flatMap(x => x.toString.toCharArray)
    println(ret(n-1))
  }

  object IO {
    @inline def read: String = scala.io.StdIn.readLine

    @inline def tokenizeLine = new java.util.StringTokenizer(read)

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

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

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

}

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

/**
  * Created by whimsy on 16/7/11.
  */

object P672A extends App {
    def work() : Int = {
//        val n : Int = StdIn.readInt()
        val n = 3
        var cnt: Int = 0

        for (i <- 1 to n) {
            var t = i
            var ab = ArrayBuffer[Int]()
            while (t > 0) {
                ab += t % 10
                t = t / 10
//                println(t)
            }

            for (j <- 0 to ab.length) {
                println(cnt)
                cnt = cnt + 1
                if (cnt == n) {
                    println(ab(j))
                    return 1
                }
            }
        }
        return 0
    }

    def work2() : Int = {
        val n = StdIn.readInt()

        var content = ""
        var cnt = 0
        while (true) {
            cnt = cnt + 1
            content += cnt

            if (content.length >= n) {
                println(content.charAt(n - 1))
                return 1
            }
        }
        return 0
    }

    work2()
}

object Solution extends App {
  val lines = io.Source.stdin.getLines()
  val n = lines.next().toInt
  val str = (0 to 1000).mkString
  println(str(n))
}


import scala.io._

object Main {

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

		var P = nextInt

		def isPrimitiveRoot(x: Int, P: Int): Boolean = {

			def rec(n: Int, powX: Int): Boolean =
				if (n == P - 1)
					powX == 1
				else
					powX != 1 && rec(n + 1, powX * x % P)

			rec(1, x)
		}

		val roots = (1 until P) filter (isPrimitiveRoot(_, P))

		println(roots.size)
	}

	val in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
	var st = new java.util.StringTokenizer("");

	def next() = {
		while (!st.hasMoreTokens())
			st = new java.util.StringTokenizer(in.readLine());
		st.nextToken();
	}

	def nextInt() = java.lang.Integer.parseInt(next());
	def nextDouble() = java.lang.Double.parseDouble(next());
	def nextLong() = java.lang.Long.parseLong(next());
}

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

object Main {

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

        def isPrimitiveRoot(x: Int, p: Int, acc: Int): Boolean =
            if (p == P - 1)
                acc == 1
            else
                acc != 1 &&
                isPrimitiveRoot(x, p + 1, acc * x % P)

        val answer = 1 until P count (x => isPrimitiveRoot(x, 1, x))

        println (answer)
    }

    class Tokenizer(in: BufferedReader, splitOn: String = " \n\t\r\f")
    {
        private var tokenizer = new StringTokenizer("")
        def readLine() = in.readLine()
        def nextToken(): String = {
            while (!tokenizer.hasMoreTokens) {
                val line = readLine
                if (line == null) return null
                tokenizer = new StringTokenizer(line, splitOn)
            }
            tokenizer.nextToken
        }
        def next[A](f: String => A) = f(nextToken)
        def nextSeq[A](f: () => A, count: Int) = (for (i <- 0 until count) yield f())
    }

    implicit val tokenizer = new Tokenizer(Console.in)

    def nextInt()(implicit t: Tokenizer) = t.next(_.toInt)
    def nextLong()(implicit t: Tokenizer) = t.next(_.toLong)
    def nextDouble()(implicit t: Tokenizer) = t.next(_.toDouble)
    def nextBigInt()(implicit t: Tokenizer) = t.next(BigInt(_))
    def nextSeq[A](f: () => A, count: Int = nextInt())(implicit t: Tokenizer) =
        (for (i <- 0 until count) yield f())
}