贪心 AC
思路:
对左端点从小到大进行排序,然后判断左右端点关系判断是否可以合并
当前维护区间:左端点=maxx, 右端点=maxy
新枚举的区间:左端点=curx, 右端点=cury
判断条件:
1.curx <= maxy 表示可以合并,合并后的区间=[maxx, max(maxy, cury)]
因为排序后一定有maxx <= curx, 合并区间有两种情况,一种是子集关系,一种是交集关系,所以右端点需要取最大值
2.curx > maxy 表示不能合并,cnt++, 更新当前维护的区间=[curx, cury] 后面再判断是否可以合并就与更新后的区间比较
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Main ins = new Main();
Scanner sc = new Scanner(System.in);
int ans = ins.solve(sc);
System.out.print(ans);
}
class Pair {
int x;
int y;
Pair(int x, int y) {
this.x = x;
this.y = y;
}
}
private int solve(Scanner sc) {
int cnt = 1;
int n = sc.nextInt();
Pair[] p = new Pair[n];
for (int i = 0; i < n; i++) {
int x = sc.nextInt(), y = sc.nextInt();
p[i] = new Pair(x, y);
}
Arrays.sort(p, new Comparator<Pair>(){
@Override
public int compare(Pair p1, Pair p2) {
return p1.x - p2.x;
}
});
int maxx = p[0].x, maxy = p[0].y;
for (int i = 1; i < n; i++) {
int curx = p[i].x, cury = p[i].y;
if (curx <= maxy) {
maxy = Math.max(maxy, cury);
} else {
cnt++;
maxx = curx; maxy = cury;
}
}
return cnt;
}
}