NYOJ-16 矩形嵌套

NYOJ-16 矩形嵌套

思路:将所有矩形按一定的次序排序,比如,排在前面的肯定不能嵌套后面的(排后面的不一定能嵌套前面的),然后,可以看见主要功能函数是递归的,而且很多节点是递归了多次的,这个时候,就可以考虑第一次递归时打上标记,在之后,就不用往下递归,直接返回值就OK拉#^_^#

代码如下:


import java.util.Arrays;
import java.util.Scanner;

public class Main {

    static class Node implements Comparable<Node>{
        int a;
        int b;
        int value;
        public Node(int a, int b) {
            this.a=a;
            this.b=b;
            value=-1;
        }
        //最开始的比较我用的a*b,后来发现这样
        //计算更少,起到的作用一样
        @Override
        public int compareTo(Node o) {
            if(a>o.a)
                return 1;
            else if(a==o.a&&b>o.b)
                return 1;
            else
                return -1;
        }
        boolean compatible(Node o){
            return this.a<o.a&&this.b<o.b;
        }
    }

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        for(int i=0;i<n;++i){
            int m=sc.nextInt();
            int tempa, tempb, t;
            Node[] nodes=new Node[m];
            for(int j=0;j<m;++j){
                tempa=sc.nextInt();
                tempb=sc.nextInt();
                if(tempb>tempa){
                    t=tempb;
                    tempb=tempa;
                    tempa=t;
                }
                nodes[j]=new Node(tempa, tempb);
            }
            Arrays.sort(nodes);
            int max, count;
            max=count=0;
            for(int j=0;j<m;++j){
                count=f(nodes, j, m);
                if(max<count)
                    max=count;
                //排在nodes[j]后面的都不到max
                //得到的f肯定不会大于max了,,
                if(max+j>m)
                    break;
            }
            System.out.println(max+1);
        }
        sc.close();
    }

    //f计算的是nodes[j]后面还能排多少个矩形
    private static int f(Node[] nodes, int j, int m) {
        if(nodes[j].value!=-1)
            return nodes[j].value;
        int max=0;
        int temp;
        for(int i=j+1;i<m;++i){
            if(nodes[j].compatible(nodes[i])){
                temp=1+f(nodes, i, m);
                if(temp>max)
                    max=temp;
            }
        }
        nodes[j].value=max;
        return max;
    }
}        
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值