算法"马戏团塔"

时间:2016-07-05 01:59:25

标签: algorithm dynamic-programming

来自"破解编码面试的问题"书:

马戏团正在设计一个由彼此站立的人组成的塔式例程 肩膀。出于实际和美学的原因,每个人必须比他或她下面的人更短更轻。考虑到马戏团中每个人的身高和体重,编写一种计算最大可能人数的方法 在这样一座塔楼里。

示例:

输入:

(ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110) 

输出:

最长的塔长6,从上到下包括:

(56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)

以下是本书的解决方案:

"当我们解决这个问题的所有问题时,我们可以理解问题实际上是如下。

我们有一对物品清单。找到最长的序列,使第一和第二项都处于非递减顺序。"

我想出了这个例子:

      {1,1} 
   {3,3} {7,2}
{6,4} {9,9} {8,5}

这里,序列的值不是非递减的顺序,但它仍然是有效的塔。而且我找不到一种方法来将相同的物品组织到另一个塔中,这些塔将具有非递减顺序的物品。我相信没有这样的方式。所以在我看来解决方案是不正确的。

我错过了什么吗?

提前致谢。

1 个答案:

答案 0 :(得分:2)

不,您的值不是非递减顺序。正如@MooseBoys评论所说,在你的情况下,第三个值的权重大于第二。 ({3,3} - > {7,2},2< 3)

问题是最长增加子序列(LIS)(DP)略有变化。

您可以根据身高对元素进行排序,然后在重量上找到最长的增加子序列。

请在下面找到java实现:

class Person implements Comparable<Person> {
    int height;
    int weight;

    public Person(int height, int weight) {
        this.height = height;
        this.weight = weight;
    }

    @Override
    public String toString() {
        return "Person{" +
                "height=" + height +
                ", weight=" + weight +
                '}';
    }

    @Override
    public int compareTo(Person p) {
        if(this.height>p.height) {
            return 1;
        } else if(this.height < p.height) {
            return -1;
        } else {
            return 0;
        }
    }
}

public class CircusTower {

    public void calculatePeople(Person[] input) {

        int weightArray[] = new int[input.length];
        String[] output = new String[input.length];
        for (int i=0;i<input.length;i++) {
            weightArray[i] = 1;
            output[i] = input[i].toString() + "";
        }
        int maxLength = 0;

        for (int i=1;i<input.length;i++) {
            for (int j=0;j<i;j++) {
                if( weightArray[j]+1>weightArray[i] && input[i].weight>input[j].weight) {
                    weightArray[i] = weightArray[j] + 1;
                    output[i] = output[j] + " " + input[i].toString();
                    if(maxLength<weightArray[i]) {
                        maxLength = weightArray[i];
                    }
                }
            }
        }

        System.out.println();


        for (int i = 0; i < input.length; i++) {
            if (weightArray[i] == maxLength) {
                System.out.println("Longest Increasing subsequence - " + output[i] + " of length = " + maxLength);
            }
        }

    }

    public static void main(String[] args) {
        CircusTower ct = new CircusTower();
        Person p1 = new Person(65,100);
        Person p2 = new Person(70,150);
        Person p3 = new Person(56, 90);
        Person p4 = new Person(75, 190);
        Person p5 = new Person(60, 95);
        Person p6 = new Person(68, 110);

        Person[] array = new Person[]{p1,p2,p3,p4,p5,p6};

        Arrays.sort(array);

        ct.calculatePeople(array);

    }

}

我正在使用LIS问题的 n square 实现,U也可以在 nlogn 中使用更好的。

希望它澄清。