prufer sequence

Learned a new pose called prufer sequence, which can be used to solve some problems about unrooted tree counting.

The prufer sequence is a coding representation of an unrooted tree. For a numbered unrooted tree with n nodes, it corresponds to a unique string of prufer codes of length n-2.

(1) Unrooted trees are converted into prufer sequences.

First define the node with degree 1 in the unrooted tree as the leaf node.

Find the leaf with the smallest number and delete it, add the node number connected to it in the sequence, and repeat until there are only 2 nodes left.

The prufer sequence corresponding to the tree in the figure below is 3, 5, 1, 3.


The specific implementation can be done with a set, which maintains a node with a degree of 1. The complexity is O(nlgn).

(2) The prufer sequence is converted into an unrooted tree.

Set the point set V={1,2,3,...,n}, take out the first element u in the prufer sequence each time, find the element v with the smallest number that does not appear in the prufer sequence in V, and give u , v connects the edges and then deletes them respectively, and finally there are two nodes left in V, and connect them with edges. The end result is an unrooted tree.

The specific implementation can also use a set to maintain the number that does not appear in the prufer sequence. The complexity is O(nlgn).

Finally, there is a very important property that the number of occurrences of a certain number in the prufer sequence + 1 is equal to the degree of the node of this number in the unrooted tree.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326865206&siteId=291194637