P1233 木棍加工 Java 实现
思路:这题的思路一定是贪心+动态规划,当遇上既有长度又有宽度的木棒的,可以先对长度进行排序(如果长度相同,则根据宽度排序),重写comparator的compare方法(Return大于0则互换元素位置)。
接下来长度的要求已经有了(根据拍好的序),在这些木棍的宽度数组中,我们需要找出宽度数组的最小不递减子序列的长度(每有一次递增的木棒出现, 我们的时间就要加1),而最小不递减子序列长度,等于这个序列的最大上升子序列长度(dilworth定理)。接下来就是套模板的最大上升子序列。
最大上升子序列:利用动态规划的思想,开一个dp数组,数组的下标表示当前元素下之前元素集合中的最大上升子序列数目。根据大小关系不断递推下去。(要注意什么时候更新dp,只有当满足大小关系的同时,更新的dp要大于原先的dp: tar[j].y > tar[i].y && dp[j] < dp[i] + 1
)
AC代码如下:
package 每日一题;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
class node {
int x ;
int y ;
node(int x,int y){
this.x = x ;
this.y = y;
}
}
public class P1233 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Scanner input = new Scanner(System.in);
//木头数目
int n = input.nextInt();
int res = 0;
node tar[] = new node[n];
int dp [] = new int [n];
for(int i = 0;i < n;i++) {
dp[i] = 1;
}
//记录木头长度
for(int i = 0 ;i < n ;i++) {
tar[i] = new node(input.nextInt(), input.nextInt());
}
Arrays.sort(tar,new Comparator<node>() {
@Override
public int compare(node o1, node o2) {
//返回值大于0则交换
if(o1.x == o2.x) {
return o2.y - o1.y;
}
else
return o2.x - o1.x;
}
});
for(int i = 0;i < tar.length;i++) {
for(int j = i;j < tar.length;j++) {
if(tar[j].y > tar[i].y && dp[j] < dp[i] + 1) {
dp[j] = dp[i] + 1;
}
}
}
for(int i = 0;i < dp.length;i++) {
if(dp[i] > res)
res = dp[i];
}
System.out.println(res);
}
}