您的位置:首页 > 编程语言 > Java开发

NYOJ-16 矩形嵌套

2016-06-20 20:41 656 查看

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 递归 矩形嵌套