8-4 water jugs

来源:互联网 发布:java开发工作经历描述 编辑:程序博客网 时间:2024/05/01 16:58

转自5hi.baidu.com/gttyatjqasmpuye/item/70aad75b550b343594eb0578

Suppose that you are given n red and n blue water jugs, all of different shapes and sizes. All red jugs hold different amounts of water, as do the blue ones. Moreover, for every red jug, there is a blue jug that holds the same amount of water, and vice versa.

It is your task to find a grouping of the jugs into pairs of red and blue jugs that hold the same amount of water. To do so, you may perform the following operation: pick a pair of jugs in which one is red and one is blue, fill the red jug with water, and then pour the water into the blue jug. This operation will tell you whether the red or the blue jug can hold more water, or if they are of the same volume. Assume that such a comparison takes one time unit. Your goal is to find an algorithm that makes a minimum number of comparisons to determine the grouping. Remember that you may not directly compare two red jugs or two blue jugs.

  1. Describe a deterministic algorithm that uses Θ(n2) comparisons to group the jugs into pairs.

  2. Prove a lower bound of Θ(n lg n) for the number of comparisons an algorithm solving this problem must make.

  3. Give a randomized algorithm whose expected number of comparisons is O(n lg n), and prove that this bound is correct. What is the worst-case number of comparisons for your algorithm?

题目很有意思,两个蓝水壶不能互相比较,两个红水壶也不能互相比较。比较只能发生在蓝水壶和红水壶之间。
解答:
a. 最朴素的两层循环就可以了,外层枚举蓝水壶,内层枚举红水壶
b. 用决策树来搞,决策树的每个内节点表示一对水壶,一蓝一红,每个内节点三个孩子,分别表示蓝大,蓝小,相等。 叶子节点总数至少为n!个,那么树高至少为n*log(n)
c. 这里模拟使用快排的思想
Assume that the red jugs are labeled with numbers 1, 2, . . . , n and so are the
blue jugs. The numbers are arbitrary and do not correspond to the volumes of
jugs, but are just used to refer to the jugs in the algorithm description. Moreover,
the output of the algorithm will consist of n distinct pairs (i, j ), where the red
jug i and the blue jug j have the same volume.
The procedure MATCH-JUGS takes as input two sets representing jugs to be
matched: R ⊆ {1, . . . , n}, representing red jugs, and B ⊆ {1, . . . , n}, representing
blue jugs. We will call the procedure only with inputs that can be
matched; one necessary condition is that |R| = |B|.
MATCH-JUGS(R, B)
    if |R| = 0 // Sets are empty
        then return
    if |R| = 1 // Sets contain just one jug each
        then let R = {r} and B = {b} output “(r, b)”
        return
    else r ← a // randomly chosen jug in R
        compare r to every jug of B
        B< ← the set of jugs in B that are smaller than r
        B> ← the set of jugs in B that are larger than r
        b ← the one jug in B with the same size as r
        compare b to every jug of R −{r} R< ← the set of jugs in R that are smaller than b
        R> ← the set of jugs in R that are larger than b
        output “(r, b)”
        MATCH-JUGS(R<, B<)
        MATCH-JUGS(R>, B>)
0 0
原创粉丝点击