Compute the minimum leaf insertions, leaf deletions, and relabels that turn one ordered labeled tree into another.
Hard9Dynamic programmingTreeNo attempts yetTime limit2sMemory limit256 MBAn XML document holds hierarchically structured data, so it is usually modeled as an ordered labeled tree. One node of the tree corresponds to one XML element, and the label of the node is the tag name of that element. One edge represents the relation between a parent element and a child element. Measuring how similar two XML documents are in structure is a common problem in information retrieval. This problem asks for the structural similarity of two XML documents represented as ordered labeled trees.
Let T be a rooted tree with one or more nodes. If every node carries a label, T is a labeled tree. Labels may repeat. If the children of every node have a fixed left to right order, T is an ordered tree.
The similarity of two ordered labeled trees T1 and T2 is often measured by the tree edit distance TED(T1,T2), the smallest number of edit operations that turn T1 into T2. Three edit operations can be applied to a tree T.
Exactly one node is inserted, deleted, or relabeled by one edit operation.
Consider the two trees in Figure 1. Applying Delete() to the leaf labeled C in T1, then Relabel(C,E), then Insert(F) turns T1 into T2. Two or fewer operations cannot turn T1 into T2, so TED(T1,T2) is 3.

(a) T1 (b) T2
Figure 1. Two ordered labeled trees
Write a program that computes the tree edit distance of two given ordered labeled trees.
The first line contains the number of test cases T. Each test case consists of two lines. The first line holds the representation of T1 and the second line holds the representation of T2.
A tree is written as follows. A tree that consists of a single root node with label l is written as (l). A tree whose root has label l and whose subtrees are S1,S2,…,Sd from left to right is written as (l(r1)(r2)⋯(rd)), where (r1),(r2),…,(rd) are the representations of S1,S2,…,Sd.
Every node label is one uppercase letter of the English alphabet. A representation contains no spaces, and the number of nodes in each tree is between 1 and 1,000.
For each test case, print on one line the minimum number of edit operations that turn T1 into T2.