贪心的区间问题的最后一题,大概看得出贪心的区间问题一般都需要排序,然后按照这个排序解决问题。
这个题依旧按照左端点排序,然后依次看是否满足条件,需要注意的是循环结束后也就是列表的元素全部试过以后发现还是没解决,那就是无解,需要特别处理。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
class Main {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static PrintWriter pw = new PrintWriter(System.out);
static int N = 100010;
static ArrayList<Pair> al = new ArrayList<>();
public static void main(String[] args) throws Exception {
String[] s = br.readLine().split(" ");
int start = Integer.parseInt(s[0]);
int end = Integer.parseInt(s[1]);
int n = Integer.parseInt(br.readLine());
for (int i = 0; i < n; i++) {
s = br.readLine().split(" ");
al.add(new Pair(Integer.parseInt(s[0]), Integer.parseInt(s[1])));
}
Collections.sort(al);
boolean flag = false;
int res = 0;
for (int i = 0; i < n; i++) {
int j = i;
int max = Integer.MIN_VALUE;
while (j < n && al.get(j).getFront() <= start) {
max = Math.max(max, al.get(j).getSecond());
j++;
}
if (max < start) break;
res++;
if (max >= end) {
flag = true;
break;
}
start = max;
i = j - 1;
}
if (flag) pw.println(res);
else pw.println(-1);
pw.flush();
pw.close();
br.close();
}
}
class Pair implements Comparable<Pair> {
int front;
int second;
public int getFront() {
return front;
}
public void setFront(int front) {
this.front = front;
}
public int getSecond() {
return second;
}
public void setSecond(int second) {
this.second = second;
}
public Pair(int front, int second) {
this.front = front;
this.second = second;
}
@Override
public int compareTo(Pair o) {
return front - o.getFront();
}
}