Tree Edit Distance

Compute the minimum leaf insertions, leaf deletions, and relabels that turn one ordered labeled tree into another.

Hard9Dynamic programmingTreeNo attempts yetTime limit2sMemory limit256 MB

Problem

An 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 TT be a rooted tree with one or more nodes. If every node carries a label, TT is a labeled tree. Labels may repeat. If the children of every node have a fixed left to right order, TT is an ordered tree.

The similarity of two ordered labeled trees T1T_1 and T2T_2 is often measured by the tree edit distance TED(T1,T2)TED(T_1, T_2), the smallest number of edit operations that turn T1T_1 into T2T_2. Three edit operations can be applied to a tree TT.

  1. Insert(x)Insert(x): insert one leaf whose label is xx. If its parent had dd children before the operation, the new node becomes the ii-th child of that parent for some ii with 1id+11 \le i \le d + 1.
  2. Delete()Delete(): delete one leaf. This operation cannot be applied to a tree with a single node.
  3. Relabel(x,y)Relabel(x, y): replace the label xx of one node by the label yy.

Exactly one node is inserted, deleted, or relabeled by one edit operation.

Consider the two trees in Figure 1. Applying Delete()Delete() to the leaf labeled C in T1T_1, then Relabel(C,E)Relabel(C, E), then Insert(F)Insert(F) turns T1T_1 into T2T_2. Two or fewer operations cannot turn T1T_1 into T2T_2, so TED(T1,T2)TED(T_1, T_2) is 3.

(a) T1T_1 (b) T2T_2

Figure 1. Two ordered labeled trees

Write a program that computes the tree edit distance of two given ordered labeled trees.

Input

The first line contains the number of test cases TT. Each test case consists of two lines. The first line holds the representation of T1T_1 and the second line holds the representation of T2T_2.

A tree is written as follows. A tree that consists of a single root node with label ll is written as (l)(l). A tree whose root has label ll and whose subtrees are S1,S2,,SdS_1, S_2, \ldots, S_d from left to right is written as (l(r1)(r2)(rd))(l(r_1)(r_2)\cdots(r_d)), where (r1),(r2),,(rd)(r_1), (r_2), \ldots, (r_d) are the representations of S1,S2,,SdS_1, S_2, \ldots, S_d.

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.

Output

For each test case, print on one line the minimum number of edit operations that turn T1T_1 into T2T_2.