题目链接为:POJ2376
题解:
import java.util.Arrays;
import java.util.Scanner;
public class Practice_区间覆盖问题 {
public static void main(String[] args) {
/*
输入测试样例:
3 10
1 7
3 6
6 10
*/
Scanner in = new Scanner(System.in);
int N = in.nextInt();//牛的个数
int T = in.nextInt();//区间(1-T)
Job[] jobs = new Job[N];
for (int i = 0; i < N; i++) {
jobs[i] = new Job(in.nextInt(), in.nextInt());
}
Arrays.sort(jobs);
int cnt = 1;
int start = 1;
int end = 1;
for (int i = 0; i < N; i++) {
int s = jobs[i].s;//起点
int e = jobs[i].e;//终点
if (i == 0 && s > start) break;
if (s <= start) {
end = Math.max(end, e);
} else {
cnt++;//计数加1
start = end + 1;//更新start
if (s > start) {
break;
} else if (s <= start) {
end = Math.max(end, e);
}
}
}
if (end < T) {//没有解
System.out.print("-1");
} else if (end >= T) {//全覆盖
System.out.print(cnt);
}
}
private static class Job implements Comparable<Job> {
int s;
int e;
public Job(int s, int e) {
this.s = s;
this.e = e;
}
@Override
public int compareTo(Job other) {
int x = this.s - other.s;//比较起点,从小到大进行排序
if (x == 0) {//起点相同,比较终点
return this.e - other.e;
}
return x;
}
}
}