Under construction

Still being built. Things may change

The Longest Chain

Interview

Time limit1sMemory limit128 MB

Summary
Given n strings, each with labeled rings a and b at its ends, find the number of vertices in the longest trail in the resulting multigraph.
Level

Medium7 of 10

Topics
Graph, DFS, Backtracking, Implementation
Solved
No attempts yet

Problem

Consider a string that has a ring attached to each end. Every ring is labeled with a positive integer, which lets us tell the strings apart, and the two rings at the ends of a single string carry two different numbers aa and bb. We write such a string as [a, b].

When there are several strings, if a ring of one string and a ring of another carry the same number, the two strings can be joined at that ring, and the result of joining them is called a chain. For example, the strings [1, 3] and [3, 4] form the chain [1, 3, 4]. A string and a chain, or a chain and another chain, can likewise be joined at rings that carry the same number.

For example, the chain [1, 3, 4] and the string [5, 1] form [5, 1, 3, 4]; the chains [1, 3, 4] and [2, 3, 5] form a shape that crosses in the middle; and the chains [1, 3, 4] and [4, 6, 1] form a closed loop.

Many shapes can arise this way. Among them, we specifically define a chain as a run of connected strings in which every ring with a given number is traversed exactly once. For example, the crossing shape formed by [1, 3, 4] and [2, 3, 5] also contains the chains [1, 3, 5] and [2, 3, 4], and the loop formed by [1, 3, 4] and [4, 6, 1] contains the chains [1, 3, 4, 6], [3, 4, 6, 1], and [4, 6, 1, 3].

The length of a chain is defined as the number of rings (numbers) it contains.

For the given strings, join everything that can be joined; the resulting figure contains one or more chains. Write a program that finds the length of the longest such chain.

Input

The first line contains a positive integer nn (1≤n≤1001 \le n \le 100), the number of strings. Each of the following nn lines contains two space-separated integers aa and bb (1≤a<b≤1001 \le a < b \le 100), the two numbers on the rings at the ends of one string.

Output

Print the length of the longest chain, followed by a newline.

Examples3

  1. Example 1

    Input
    7
    1 3
    3 4
    1 4
    2 7
    5 7
    6 7
    1 7
    
    Expected output
    5
    
  2. Example 2

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

    Input
    7
    1 3
    2 4
    3 5
    4 6
    6 7
    2 6
    4 7
    
    Expected output
    4