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---

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值