You are given a rooted tree with $$$n$$$ vertices numbered $$$1, 2, .. n$$$, where every edge has a character on it. You want to find an euler tour, such that the string formed by the concatenation of the characters on the edges is minimized. Formally, let $$$c(x, y)$$$ denote the character written on the edge $$$(x, y)$$$. Initialize an empty string $$$S$$$, and order the children of each node arbitrarily and then run dfs(1):
dfs(s):
for v in children(s):
append c(s, v) to S
dfs(v)
append c(s, v) to S
In the end, you get a string $$$S$$$ of length $$$2n - 2$$$. What is the lexicographically minimum $$$S$$$ that you can achieve?
The first line contains $$$n (2 \leq n \leq 5 \cdot 10^5)$$$, the number of vertices in the tree. The $$$i^{th}$$$ of the next $$$n - 1$$$ lines contains two integers, $$$p_i$$$ and $$$c_i$$$, where $$$p_i$$$ is the parent of the node $$$i + 1$$$, and $$$c_i$$$ is the character write on the edge between $$$i + 1$$$ and $$$p_i$$$ respectively. Here $$$1 \leq p_i \lt i$$$ and $$$c_i$$$ is a lower case english alphabet.
Print the lexicographically minimum possible $$$S$$$.
5 1 a 2 c 2 b 1 a
aaabbcca
The tree is the following:
The optimal euler tour is $$$(1, 5, 1, 2, 4, 2, 3, 2, 1)$$$