Cracking the coding interview--Q9.7

题目

原文:

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)

解答

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

import java.util.Arrays;

class Q9_7{
	public static int k=1;
	public static void main(String[] args){
		Person[] person=new Person[]{new Person(65,100),new Person(70,150),
			new Person(56,90),new Person(75,190),new Person(60,95),new Person(60,150),new Person(68,110)};
		//sorting by height
		Arrays.sort(person);
		System.out.println(arrange(person));
	}

	public static int arrange(Person[] person){
		int[] d=new int[100];
		d[0]=person[0].weight;
		for(int i=1;i<person.length;++i){
			if(person[i].weight>=d[k-1])
				d[k++]=person[i].weight;
			else{
				int j;
				for(j=k-1;j>=0&&d[j]>person[i].weight;--j);
				d[j+1]=person[i].weight;
			}
		}
		return k;
	}

}

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

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

	public int compareTo(Person o){
		if(this.height>o.height){
			return 1;
		}else{
			return -1;
		}
	}
}

---EOF---

你可能感兴趣的:(待优化)