矩形嵌套

 1 import java.util.*;
 2 import java.math.*;
 3 public class Main {
 4 
 5     public static void main(String[] args) {
 6         
 7         Solution s = new Solution();
 8         Scanner sc = new Scanner(System.in);
 9         int N = sc.nextInt();
10         int[] result = new int[N];
11         
12         for(int i = 0; i < N; i++) {
13             int n = sc.nextInt();
14             block[] groupBlock = new block[n];
15             
16             for(int j = 0; j < n; j++) {
17                 s.insertSort(groupBlock, new block(sc.nextInt(), sc.nextInt()), j);
18             }
19             result[i] = s.getResult(groupBlock);
20         }
21         for(int i : result) {
22             System.out.println(i);
23         }
24         sc.close();
25     }
26 }
27 
28 class Solution {
29     public int getResult(block[] groupBlock) {
30         int N = groupBlock.length;
31         int[] states = new int[N];
32         int result = 0;
33         for(int i = 0; i < N; i++) {
34             int maxNum = 1;
35             for(int j = 0; j < i; j++) {
36                 if(groupBlock[i].a > groupBlock[j].a && groupBlock[i].b > groupBlock[j].b) {
37                     //保证可以嵌套
38                     maxNum = states[j] + 1 > maxNum ? states[j] + 1: maxNum; //修改最大值
39                 }
40             }
41             states[i] = maxNum;
42             if(maxNum > result)
43                 result = maxNum;
44         }
45         return result;
46     }
47     public void insertSort(block[] groupBlock, block blo, int j) {
48         while(j > 0 && groupBlock[j - 1].a > blo.a) {
49             groupBlock[j] = groupBlock[j - 1];
50             j--;
51         }
52         groupBlock[j] = blo;
53     }
54 }
55 
56 class block {
57     public int a = 0;
58     public int b = 0;
59     public block() { };
60     public block(int length, int width) {
61         a = length >= width ? length : width;
62         b = length <= width ? length : width;
63     }
64 }

这道题真的让我苦思冥想好久啊,原因在与完全没有学过动态规划强行去解这道题。自己在初期的思路完全走了错误的方向,而且还根深蒂固。不由得让我想起我遇到的第一道动态规划,也是靠蛮力硬解,导致了完全陷入了成堆的“也许可行”的逻辑控制当中,不得不说还是应当学习别人的先进想法再来动手。
解法很是明白,当然这和刘佳汝大神更优化的解法相差还是十分遥远,不过算是大众的思路了,先排序,再用类似LIS的方法求解。

原文地址:https://www.cnblogs.com/dsj2016/p/5231620.html