AcWing 905. 区间选点Java题解
原题链接
简单
作者:
大瓜娃子
,
2024-10-27 13:01:43
,
所有人可见
,
阅读 10
import java.io.*;
import java.util.*;
class seg {
int l, r;
seg(int l, int r) {
this.l = l;
this.r = r;
}
}
class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
int n = Integer.parseInt(in.readLine());
seg[] segs = new seg[n]; // 只创建 n 个 seg 对象
for (int i = 0; i < n; i++) {
String[] arr = in.readLine().split(" ");
int l = Integer.parseInt(arr[0]);
int r = Integer.parseInt(arr[1]);
segs[i] = new seg(l, r);
}
Arrays.sort(segs, (a, b) -> a.r - b.r); //全局变量创建segs会报错,因为不能排序null
int res = 0;
int end = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
seg cur = segs[i];
if (end < cur.l) {
res++;
end = cur.r;
}
}
out.write(res + ""); // 输出结果并换行
in.close();
out.flush();
out.close();
}
}