The Longest Chain
InterviewTime limit1sMemory limit128 MB
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 and . 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 (), the number of strings. Each of the following lines contains two space-separated integers and (), the two numbers on the rings at the ends of one string.
Output
Print the length of the longest chain, followed by a newline.