您的位置:首页 > 其它

Cracking the coding interview--Q9.7

2014-12-15 20:19 239 查看
原文:

A circus is designing a tower routine consisting of people standing atop one another’s shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the heights and weights of each person
in the circus, write a method to compute the largest possible number of people in such a tower.

EXAMPLE:

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

Output: The longest tower is length 6 and includes from top to bottom: (56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)

译文:

马戏团设计了这样一个节目:叠罗汉。一群人往上叠,每个人都踩在另一个人的肩膀上。 要求上面的人要比下面的人矮而且比下面的人轻。给出每个人的身高和体重, 写一个函数计算叠罗汉节目中最多可以叠多少人?

例子:

输入(身高 体重):(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))

想要叠最多人,并且要求从顶到底身高和体重逐渐减小,所以可以先按照一个指标排序,然后寻找另一个指标的最长递增子序列,代码如下:

package chapter_9_SortingandSearching;

import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

class Person {
private int height;
private int weight;

public Person() {

}
public Person(int height, int weight) {
this.height = height;
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
}

class PersonComparator implements Comparator<Person> {

public int compare(Person p1, Person p2) {
if(p1.getHeight() > p2.getHeight()) {
return 1;
} else if(p1.getHeight() < p2.getHeight()) {
return -1;
} else {
return 0;
}
}
}

/**
*
* 马戏团设计了这样一个节目:叠罗汉。一群人往上叠,每个人都踩在另一个人的肩膀上。
* 要求上面的人要比下面的人矮而且比下面的人轻。给出每个人的身高和体重, 写一个函数计算叠罗汉节目中最多可以叠多少人?
*
*/
public class Question_9_7 {

public static int getMaxHeight(Person[] persons) {
int len = persons.length;
int[] wei = new int[len];
wei[0] = persons[0].getWeight();
int maxLen = 1;
for(int i=1; i<len; i++) {
if(persons[i].getWeight() >= wei[maxLen-1]) {
wei[maxLen ++] = persons[i].getWeight();
} else {
int j = maxLen-1;
for(;j >=0 && wei[j] > persons[i].getWeight() ; j--);
wei[j+1] = persons[i].getWeight();
}
}
return maxLen;
}

public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
scanner.nextLine();
Person[] persons = new Person[num];
for(int i=0; i<num; i++) {
persons[i] = new Person();
int height = scanner.nextInt();
int weight = scanner.nextInt();
scanner.nextLine();
}
// 身高排好序后, 身高这个指标就都是满足叠罗汉的要求了,剩下的就看体重。
// 就只要在体重那个维度找到最长的递增子序列就可以了。
Arrays.sort(persons, new PersonComparator());
System.out.println("Hei:" + getMaxHeight(persons));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法