Palindrome Tree

4

2 votes
Hard
Problem

Let there be a tree of N vertices numbered 1 to N. On each node there is a single character, let the character on the ith node be C[i]. Count the number of ways to select 2 distinct nodes i and j such that the string spelled out by the letters on the simple path from i to j C[i]...C[j] in any order can form a palindrome. Note that (i,j) and (j,i) are two different choices.

Input format

First line of input contains single integer N: The number of nodes in the tree.

Second line contains N space-separated lower-case English characters: The ith of which represents C[i].

Next N-1 lines contain 2 integers each, representing a single edge. It is guaranteed the given edges form a tree.

Output format

Output a single integer: the number of ways of selecting 2 distinct nodes i and j to satisfy conditions in the problem statement

Constraints

1N100000

Time Limit: 5
Memory Limit: 256
Source Limit:
Explanation

Here: (1,3),(1,4),(1,5),(2,4),(2,5),(3,1),(3,5),(4,1),(4,2),(5,1),(5,2),(5,3) are all valid pairs. Note that each ordered pair is counted once even though there might be many possible palindromes formed with the letters along the path. Also, for any path (i,j) that is counted (j,i) is counted as well.

Editor Image

?