import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class SectionCoincide {
static class Line {
int x, y;
public Line(int x, int y) {
this.x = x;
this.y = y;
}
boolean isInclude(Line line) {
return x <= line.x && y >= line.y;
}
// 排序后使用,前提是 line 在this的右边
public boolean join(Line line) {
if (y < line.x)
return false;
y = line.y;
return true;
}
public String toString() {
return "[" + x + "," + y + "]";
}
}
/**
* 将其以 x 排序,并合成不相交的 然后用二分查找在这些不相交的 line 中查找看是否有一个能完全覆盖目标
*/
public static void execute(Line[] lines, Line target) {
Arrays.sort(lines, new Comparator<Line>() {
@Override
public int compare(Line o1, Line o2) {
return o1.x < o1.x ? -1 : (o1.x > o2.x ? 1 : 0);
}
});
List<Line> list = new ArrayList<Line>();
list.add(lines[0]);
int pos = 0;
for (int i = 1, len = lines.length; i < len; i++) {
if (!list.get(pos).join(lines[i])) {
list.add(lines[i]);
pos++;
}
}
// 利用 二分查找在 list 中找出,将target.x,target.y 找出在哪一个区间,看它们是否同一区间
System.out.println(list + " " + target);
int a = getIndex(list, target.x);
int b = getIndex(list, target.y);
System.out.println(a == b ? "Yes" : "No");
}
static int getIndex(List<Line> list, int k) {
int from = 0, to = list.size() - 1;
while (from <= to) {
int mid = (from + to) >> 1;
if (k >= list.get(mid).x && k <= list.get(mid).y)
return mid;
else if (k < list.get(mid).x)
to = mid - 1;
else
from = mid + 1;
}
return -1;
}
static final int SIZE = 10;
public static void main(String args[]) {
Scanner cin = new Scanner(
SectionCoincide.class.getResourceAsStream("Line.txt"));
int g = cin.nextInt();
while (g-- > 0) {
int n = cin.nextInt();
Line[] lines = new Line[n];
for (int i = 0; i < n; i++) {
int x = cin.nextInt();
int y = cin.nextInt();
lines[i] = new Line(x, y);
}
int targetx = cin.nextInt();
int targety = cin.nextInt();
Line target = new Line(targetx, targety);
execute(lines, target);
}
}
}
编程之美--区间重合判断
最新推荐文章于 2021-05-20 20:04:09 发布