Visiting Cows
InterviewTime limit1sMemory limit128 MB
Given a tree with N vertices, choose the largest set of vertices with no two adjacent, which is the maximum independent set on a tree.
- Level
Medium6 of 10
- Topics
- Tree, Dynamic programming, DFS, Graph
- Solved
- No attempts yet
Problem
After many weeks of hard work, Bessie is finally getting a vacation! Being the most social cow in the herd, she wishes to visit her () cow friends, conveniently numbered .
The cows have set up an unusual road network with exactly roads. Each road connects a pair of cows and (, , ), and there is a unique path of roads between any two cows. In other words, the road network forms a tree.
Farmer John wants Bessie to come back to the farm soon, so he has told her that if two cows are directly connected by a road, she may not visit them both. Of course, Bessie would like her vacation to be as long as possible, so she wants to determine the maximum number of cows she can visit.
Input
- Line 1: A single integer .
- Lines 2 to : Each line describes one road with two space-separated integers and .
Output
- Line 1: A single integer, the maximum number of cows that Bessie can visit.
Hint
Bessie knows 7 cows. Cows 6 and 2 are directly connected by a road, as are cows 3 and 4, cows 2 and 3, and so on. The illustration below shows the roads that connect the cows:
1--2--3--4
|
5--6--7
Bessie can visit four cows. One of the best combinations is two cows from the top row and two from the bottom row. She cannot visit cow 6, because that would prevent her from visiting cows 5 and 7; so she visits cows 5 and 7 instead. From the top row she can visit any of {1, 3}, {1, 4}, or {2, 4}.