Candelabra
Time limit5sMemory limit1024 MB
Given a tree of n vertices labeled with letters a to t, find the longest path subsequence with no palindromic substring of length 2 or more.
- Level
Hard9 of 10
- Topics
- Divide and conquer, Tree, Dynamic programming, Bit manipulation
- Solved
- No attempts yet
Statement
A terrible Monster lives in a cursed castle hidden deep in a dark forest. Only a beautiful girl who loves him as he is can melt the ice in his heart and restore his human form.
Breaking the curse is not easy. The girl must find the longest melodic subsequence written on the vertices of a candelabra and recite it under the full moon.
The candelabra is a connected graph with vertices and edges. Each vertex has a lowercase Latin letter from 'a' to 't' written on it.
A path is a sequence of vertices in which each vertex appears at most once and every two adjacent vertices are connected by an edge. A subsequence is a path with some elements removed, keeping the order of the remaining elements. A substring is a subsequence with zero or more vertices removed from the beginning and the end. A subsequence is called melodic if it has no substring of length greater than one that equals its reverse.
Input
The first line contains (), the number of vertices. Each of the next lines contains two integers and (, ), the vertices joined by an edge. There is exactly one path between any two vertices. The last line contains a string of lowercase letters from 'a' to 't', where the -th letter is written on vertex .
Output
Print one integer, the maximum length of a melodic subsequence.