简体   繁体   中英

Programmatically determine whether an array could be the result of a Weighted Quick Union algorithm on a set of 10 items?

I'd like to be able to programmatically examine an array and determine whether or not it could have been the result of a Weighted Quick Union algorithm. For those of us who need a refresher, a java implementation of Weighted Quick Union is here .

The basic idea of the weighted quick union algorithm is that is always connects the smaller tree to the larger one in order to minimize height, thus optimizing any traversal functions.

For example, an array that looks like 8 4 8 8 8 3 8 3 9 7 could not be the result of Weighted Quick Union because it contains a cycle, 9->7->3->8->9

An array like 8 0 9 3 6 6 0 4 8 0 cannot be a weighted quick union because the height of the trees together is 4, which is more than log(N) (where N is 10, the size of the initial array).

However, an array like 0 1 2 8 4 1 1 7 8 9 could have been the result of a weighted quick union.

I'd like to write a Java function like this:

public static boolean canBeResultOfWeightedQuickUnion(int[] id){
    //returns whether or not the given array of ints could have been the result of a weighted quick union
}

How could I go about writing a method like this, ideally using the data structure available here ?

"An array like *** cannot be a weighted quick union because the height of the trees together is 4, which is more than log(N) (where N is 10, the size of the initial array)."

In fact the maximum height in this case is ceil(log_2(N)), which is 4. To check this, just keep merging trees with the same height from the start

This property remains for all subtrees, and it is a very good answer for your question since you can just check this property.

The question that stills is how can you do this with most efficiency. I suppose that you just received an array and is checking it. So no other info is available. If this is the case, you can just create a auxiliary array for the height. Then you must go throught the id array, find the leafs and in a second step recursively go from the leafs to the roots updating the values of the heights and comparing to the number of elements in the subtree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM