洛谷P1233 木棍加工 动态规划 最大上升子序列

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);
	}

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值