在x数轴上给出众多线段(已知线段起点与终点),求给定一个线段,并查询该线段与上述众多线段中几条线段相交。创建有序二叉树,节点为众多线段,顺序由线段的起点决定,并且每个节点增加一个域存放该节点的子树中能到达的最右端的值。
class RangeTree {
private int begin; //起点
private int end; //终点
private int maxEnd; //能到达的最右端
private RangeTree l;
private RangeTree r;
public RangeTree(int begin, int end) {
this.begin = begin;
this.end = end;
this.maxEnd = end;
}
//添加
public void add(RangeTree x) {
if (x.begin < begin) {
if (l == null) {
l = x;
} else {
l.add(x);
}
} else {
if (r == null) {
r = x;
} else {
r.add(x);
}
}
if (l != null && l.end > maxEnd)
maxEnd = l.end;
if (r != null && r.end > maxEnd)
maxEnd = r.end;
}
//获取线段相交的数量
public int getOverCnt(int a, int b) {
int n = 0;
if(a >= maxEnd) {
return 0;
}
if (isOver(begin, end, a, b))
n++;
if(l!=null) {
n += l.getOverCnt(a, b);
}
if(r!=null) {
n += r.getOverCnt(a, b);
}
return n;
}
//判断是否相交
private boolean isOver(int a1, int b1, int a2, int b2) {
int len1 = (b1 - a1) + (b2 - a2);
int maxB = Math.max(b1, b2);
int minA = Math.min(a1, a2);
int len2 = maxB - minA;
return len2 < len1;
}
}
public class RangeTreeTest {
public static void main(String[] args) {
RangeTree root = new RangeTree(3, 5);
root.add(new RangeTree(1, 3));
root.add(new RangeTree(2, 4));
root.add(new RangeTree(5, 7));
root.add(new RangeTree(8, 10));
root.add(new RangeTree(4, 8));
root.add(new RangeTree(2, 5));
int cnt = root.getOverCnt(1, 5);
System.out.println(cnt);
}
}