Tree Edit Distance
Time limit2sMemory limit256 MB
Compute the minimum leaf insertions, leaf deletions, and relabels that turn one ordered labeled tree into another.
- Level
Hard9 of 10
- Topics
- Dynamic programming, Tree
- Solved
- No attempts yet
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 be a rooted tree with one or more nodes. If every node carries a label, is a labeled tree. Labels may repeat. If the children of every node have a fixed left to right order, is an ordered tree.
The similarity of two ordered labeled trees and is often measured by the tree edit distance , the smallest number of edit operations that turn into . Three edit operations can be applied to a tree .
- : insert one leaf whose label is . If its parent had children before the operation, the new node becomes the -th child of that parent for some with .
- : delete one leaf. This operation cannot be applied to a tree with a single node.
- : replace the label of one node by the label .
Exactly one node is inserted, deleted, or relabeled by one edit operation.
Consider the two trees in Figure 1. Applying to the leaf labeled C in , then , then turns into . Two or fewer operations cannot turn into , so is 3.

(a) (b)
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 . Each test case consists of two lines. The first line holds the representation of and the second line holds the representation of .
A tree is written as follows. A tree that consists of a single root node with label is written as . A tree whose root has label and whose subtrees are from left to right is written as , where are the representations of .
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 into .