Problem:
Multi-ending Story

You are a programmer who loves bishojo games (a sub-genre of dating simulation games).
A game, which is titled "I * C * P * C!" and was released yesterday, has arrived to you just now.
This game has multiple endings. When you complete all of those endings, you can get a special figure of the main heroine, Sakuya.
So, you want to hurry and play the game!
But, let's calm down a bit and think how to complete all of the endings in the shortest time first.

In fact, you have a special skill that allows you to know the structure of branching points of games.
By using the skill, you have found out that all of the branching points in this game are to select two choices "Yes" or "No", and once a different choice is taken the branched stories flow to different endings; they won't converge any more, like a binary tree.
You also noticed that it takes exactly one minute to proceed the game from a branching point to another branching point or to an ending.
In addition, you can assume it only takes negligible time to return to the beginning of the game (``reset'') and to play from the beginning to the first branching point.

The game has an additional feature called "Quick Save", which can significantly reduce the playing time for completion.
The feature allows you to record the point where you are currently playing and return there at any time later.
You can record any number of times, but you can hold only the last recorded point.
That is, when you use Quick Save, you overwrite the previous record. If you want to return to the overwritten point, you must play the game from the beginning once again.

Well, let's estimate how long it will take for completing all of the endings in the shortest time.

Input

A data set is given in the following format.

The first line of the data set contains one integer N (2 \leq N \leq 500{,}000), which denotes the number of the endings in this game.
The following N-1 lines describe the branching points.
The i-th line describes the branching point of ID number i and contains two integers Yes_i and No_i (i + 1 \leq Yes_i, No_i \leq N), which denote the ID numbers of the next branching points when you select Yes or No respectively.
Yes_i = N means that you can reach an ending if you select Yes, and so for No_i = N.
The branching point with ID 1 is the first branching point.
The branching points with ID between 2 and N-1 (inclusive) appear exactly once in Yes_i's and No_i's.

Output

Print the shortest time in a line.

Sample Input 1

4
2 3
4 4
4 4

Output for the Sample Input 1

6

Sample Input 2

5
5 2
3 5
5 4
5 5

Output for the Sample Input 2

8

Solution in Scala (judge verdict: Accepted)

import scala.collection.immutable.Nil
import scala.collection.mutable

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

  val n = readInt
  val events = Array.tabulate(n - 1){_ ⇒
    val Array(l, r) = readLine.trim.split(' ').map(_.toInt)
    Event(l, r)
  }
  val branch = Branch(events)
  println(branch.canSaveTime)
  case class Event(left: Int, right: Int)
  object Branch {
    def apply(events: Array[Event]): Branch = {
      val refCount = Array.tabulate(events.length + 1){_ ⇒ 0}
      val reference = Array.tabulate(events.length + 1){_ ⇒ Nil: List[Int]}
      for (i ← events.indices){
        val Event(left, right) = events(i)
        refCount(i) += 2
        reference(left - 1) ::= i
        reference(right - 1) ::= i
      }
      val depth = calDepth(events)
      val branches = Array.tabulate(events.length + 1){_ ⇒ Ending: Branch}
      val queue = mutable.Queue[Int](events.length)
      while (queue.nonEmpty){
        val top = queue.dequeue()
        for (prev ← reference(top)) {
          refCount(prev) -= 1
          if (refCount(prev) == 0){
            queue.enqueue(prev)
            val Event(left, right) = events(prev)
            branches(prev) = Choice(depth(prev), branches(left - 1), branches(right - 1))
          }
        }
      }
      branches(0)
    }
    private[this] def calDepth(events: Array[Event]): Array[Int] = {
      val depth = Array.tabulate(events.length + 1){_ ⇒ -1}.also{d ⇒ d(0) = 0
        d(events.length) = 0}
      val queue = mutable.Queue[Int](0)
      while (queue.nonEmpty){
        val top = queue.dequeue()
        val Event(left, right) = events(top)
        if (depth(left - 1) == -1) {
          depth(left - 1) = depth(top) + 1
          queue.enqueue(left - 1)
        }
        if (depth(right - 1) == -1){
          depth(right - 1) = depth(top) + 1
          queue.enqueue(right - 1)
        }
      }
      depth
    }

  }
  sealed trait Branch {
    def endingCount: Int
    def canSaveTime: Long
    def cannotSaveTime: Long
  }
  case object Ending extends Branch {
    override def endingCount: Int = 1
    override def canSaveTime: Long = 0
    override def cannotSaveTime: Long = 0
  }
  case class Choice(depth: Int, left: Branch, right: Branch) extends Branch {
    override val endingCount = left.endingCount + right.endingCount
    override val canSaveTime: Long = List(
      left.cannotSaveTime + right.cannotSaveTime + endingCount,
      left.cannotSaveTime + right.canSaveTime + left.endingCount + 1,
      left.canSaveTime + right.cannotSaveTime + right.endingCount + 1,
      left.canSaveTime + right.canSaveTime + depth + 2
    ).min
    override val cannotSaveTime: Long = left.cannotSaveTime + right.cannotSaveTime + endingCount
  }
  implicit class Scope[T](val value: T) extends AnyVal {
    @inline
    def also(@inline func: T ⇒ Unit): T = {
      func(value)
      value
    }
    @inline
    def let[A](@inline func: T ⇒ A): A = func(value)
  }
}