POJ1065–贪心问题
一、题目链接
二、题目内容
There is a pile of n wooden sticks. The length and weight of each stick are known in advance. The sticks are to be processed by a woodworking machine in one by one fashion. It needs some time, called setup time, for the machine to prepare processing a stick. The setup times are associated with cleaning operations and changing tools and shapes in the machine. The setup times of the woodworking machine are given as follows:
(a) The setup time for the first wooden stick is 1 minute.
(b) Right after processing a stick of length l and weight w , the machine will need no setup time for a stick of length l’ and weight w’ if l <= l’ and w <= w’. Otherwise, it will need 1 minute for setup.
You are to find the minimum setup time to process a given pile of n wooden sticks. For example, if you have five sticks whose pairs of length and weight are ( 9 , 4 ) , ( 2 , 5 ) , ( 1 , 2 ) , ( 5 , 3 ) , and ( 4 , 1 ) , then the minimum setup time should be 2 minutes since there is a sequence of pairs ( 4 , 1 ) , ( 5 , 3 ) , ( 9 , 4 ) , ( 1 , 2 ) , ( 2 , 5 ) .
Input
The input consists of T test cases. The number of test cases (T) is given in the first line of the input file. Each test case consists of two lines: The first line has an integer n , 1 <= n <= 5000 , that represents the number of wooden sticks in the test case, and the second line contains 2n positive integers l1 , w1 , l2 , w2 ,…, ln , wn , each of magnitude at most 10000 , where li and wi are the length and weight of the i th wooden stick, respectively. The 2n integers are delimited by one or more spaces.
Output
The output should contain the minimum setup time in minutes, one per line.
Sample Input
3
5
4 9 5 2 2 1 3 5 1 4
3
2 2 1 1 2 2
3
1 3 2 2 3 1
Sample Output
2
1
3
翻译
现有n根木棍等待加工,每根木棍由长度和宽度构成,加工器在放入第一根木棍的时候有一分钟的准备时间,然后在后面塞入木棍的长和宽都比上一根木棍小的木棍将不需要准备时间,否则就需要重新准备一分钟。请你找到处理给定的n根木棍的最短设置时间。例如,如果您有五根长度和重量对分别为(9,4),(2,5),(1、2),(5,3)和(4,1)的摇杆,则最小设置时间应该是2分钟,因为有对(4,1),(5,3),(9,4),(1,2),(2,5)对的序列。
三、题意拆解
- 题目需要我们找到最佳方案,使得准备时间最短然后输出最短时间。
- 首先,我们会得到一批有两个属性的木棍,然后我们需要自己把它排序好 (注意:题目给的序列是没有排序好的木棍序列) ,然后我们需要根据这个最佳排序序列输出最少准备时间。
- 那么什么是最佳序列? 当后面的木棍都比序列前一个木棍小(长、宽都小即为小)的子序列最少 就是最佳序列,这种子序列我称它为下降子序列。
- 比如:4 9 5 2 2 1 3 5 1 4 这个序列
最佳排序应该是4 9 3 5 1 4| 5 2 2 1
因为这样子他的下降子序列只有两个,是最佳方案。
四、解题思路
因为题目要求我们找到最快速度的方法,那么我们直接把获取到的木棍根据它单个属性排序,那么第一个木棍就是最“大”的那个木棍,它必须成为下降子序列的首元素,然后我们遍历木棍,将它的序列排出来,得到第一个序列,而后继续重新遍历这些木棍,把剩余木棍里最大的木棍拿出来成为新的下降子序列。
例如:
4-9 5-2 2-1 3-5 1-4
我们先将其排序,我这里按照长度来排序,排序后结果是
5-2 4-9 3-5 2-1 1-4
然后我们找出第一个下降子序列
5-2 2-1
然后剩下的序列就是
4-9 3-5 1-4
这也同时是第二个下降子序列,所以结果是2。
五、参考代码
做法一:暴力
//
// Created by Verber.
//