时间限制:C/C++ 1秒,其他语言2秒

空间限制:C/C++ 256M,其他语言512M

小Q在进行一场竞技游戏,这场游戏的胜负关键就在于能否能争夺一条长度为L的河道,即可以看作是[0,L]的一条数轴。
这款竞技游戏当中有n个可以提供视野的道具−真视守卫,第i个真视守卫能够覆盖区间[x,y]。现在小Q想知道至少用几个真视守卫就可以覆盖整段河道。

输入描述:

输入包括n+1行。

第一行包括两个正整数n和L(1<=n<=10> ,1<=L<=10> )
接下来的n行,每行两个正整数x> ,y> (0<=x> <=y> <=10> ),表示第i个真视守卫覆盖的区间。

输出描述:

一个整数,表示最少需要的真视守卫数量, 如果无解, 输出-1。

输入例子1:

4 6 3 6 2 4 0 2 4 7

输出例子1:

3

暴力贪心

  1. import java.util.Scanner;
  2. public class Solution {
  3. public static void main(String[] args) {
  4. Scanner sc = new Scanner(System.in);
  5. int n = sc.nextInt();
  6. int L = sc.nextInt();
  7. int[][] xy = new int[2][n];
  8. for (int i = 0; i < n; i++) {
  9. xy[0][i] = sc.nextInt();
  10. xy[1][i] = sc.nextInt();
  11. }
  12. sc.close();
  13. int ans = 0;
  14. int f = 0;
  15. while (f <= L) {
  16. if (func(xy, f) > f) {
  17. f = func(xy, f);
  18. } else {
  19. System.out.println(-1);
  20. }
  21. ans++;
  22. if (f >= L) {
  23. System.out.println(ans);
  24. }
  25. }
  26. }
  27. public static int func(int[][] xy, int f) {
  28. // x[0][i] < f, max(x[1][i]>f)
  29. int ans = f;
  30. for (int i = 0; i < xy[0].length; i++) {
  31. if (xy[0][i] <= f && xy[1][i] > ans) {
  32. ans = xy[1][i];
  33. }
  34. }
  35. return ans;
  36. }
  37. }

贪心-优化

先进行排序、贪心

  1. import java.util.Arrays;
  2. import java.util.Comparator;
  3. import java.util.Scanner;
  4. import java.util.Stack;
  5. public class Solution {
  6. public static void main(String[] args) {
  7. Scanner sc = new Scanner(System.in);
  8. int n = sc.nextInt();
  9. int L = sc.nextInt();
  10. int[][] xy = new int[n][2];
  11. for (int i = 0; i < n; i++) {
  12. xy[i][0] = sc.nextInt();
  13. xy[i][1] = sc.nextInt();
  14. }
  15. sc.close();
  16. Arrays.sort(xy, new Comparator<int[]>() {
  17. public int compare(int[] o1, int[] o2) {
  18. return o1[0] == o2[0] ? o1[1] - o2[1] : o1[0] - o2[0];
  19. }
  20. });
  21. if (xy[0][0] > 0) {
  22. System.out.println(-1);
  23. return;
  24. }
  25. // r向右的范围,max
  26. int ans = 1, idx = 0, r = xy[0][1], max = 0;
  27. while (r < L) {
  28. max = 0;
  29. boolean f = false;
  30. while (idx < n && xy[idx][0] <= r) {
  31. f = true;
  32. // max 此刻的最右范围
  33. max = Math.max(max, xy[idx][1]);
  34. idx++;
  35. }
  36. if (!f) {
  37. System.out.println("-1");
  38. return;
  39. }
  40. r = max;
  41. ans++;
  42. }
  43. System.out.println(ans);
  44. }
  45. }