import scala.annotation.tailrec
import scala.collection.mutable

object Main extends App {
  import scala.io.StdIn._
  val n = readInt()
  val stones = Array.fill(n){
    val Array(r, c) = readLine.trim.split(' ').map(_.toInt)
    (r - 1, c - 1)
  }.sortBy(_._1)
  val rowCount = Array.fill(n){0}
  val columnCount = Array.fill(n){0}
  for ((r, c) ← stones) {
    rowCount(r) += 1
    columnCount(c) += 1
  }
  if (rowCount.exists(_ > 1) || columnCount.exists(_ > 1)) {
    println(-1)
  }else {
    val columnPosition = stones.map{_._2}
    var count = 0
    for (i ← columnPosition.indices) {
      while (columnPosition(i) != i){
        count += 1
        val temp = columnPosition(i)
        columnPosition(i) = columnPosition(columnPosition(i))
        columnPosition(temp) = temp
      }
    }
    println(count)
  }
}

