This page is still under construction.

Parts of this page are still being built. What you see may change.

Primitivus

Time limit3sMemory limit128 MB

Summary
Given a set of ordered pairs, find the shortest sequence in which every pair appears consecutively at least once.
Level

Medium7 of 10

Topics
Graph, Shortest path, Dynamic programming, Bit manipulation
Solved
No attempts yet

Problem

The genetic code of the abstract organism Primitivus recurencis is a sequence of natural numbers K=(a1,a2,…,an)K = (a_1, a_2, \dots, a_n). A feature of a primitivus is any ordered pair (l,r)(l, r) that appears consecutively in the genetic code, that is, there exists an index ii such that ai=la_i = l and ai+1=ra_{i+1} = r. A genetic code never contains a feature of the form (p,p)(p, p): no value is ever immediately followed by itself.

You are given a set of features. Write a program that:

  • reads the list of features from standard input,
  • computes the length of the shortest genetic code that contains all of the given features,
  • writes that length to standard output.

Input

The first line contains one positive integer nn, the number of distinct features. Each of the next nn lines contains two natural numbers ll and rr separated by a single space (1≤l≤10001 \le l \le 1000, 1≤r≤10001 \le r \le 1000, l≠rl \ne r), describing one feature (l,r)(l, r). No feature appears more than once.

Output

Print a single integer: the length of the shortest genetic code that contains every feature from the input.

Hint

For the example input, all features appear in this genetic code of length 15:

(8,5,1,4,2,3,9,6,4,5,7,6,2,8,6)(8, 5, 1, 4, 2, 3, 9, 6, 4, 5, 7, 6, 2, 8, 6).

Examples4

  1. Example 1

    Input
    12
    2 3
    3 9
    9 6
    8 5
    5 7
    7 6
    4 5
    5 1
    1 4
    4 2
    2 8
    8 6
    
    Expected output
    15
    
  2. Example 2

    Input
    1
    1 2
    
    Expected output
    2
    
  3. Example 3

    Input
    2
    1 2
    2 1
    
    Expected output
    3
    
  4. Example 4

    Input
    3
    1 2
    2 3
    3 1
    
    Expected output
    4