Java中算法提高之线段和点的示例分析

这篇文章主要为大家展示了“Java中算法提高之线段和点的示例分析”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Java中算法提高之线段和点的示例分析”这篇文章吧。

一、算法提高 线段和点

1、时间限制

1.0s 内存限制:256.0MB

2、问题描述 

有n个点和m个区间,点和区间的端点全部是整数,对于点a和区间[b,c],若a>=b且a<=c,称点a满足区间[b,c]。
  求最小的点的子集,使得所有区间都被满足。

3、输入格式

第一行两个整数n m
  以下n行 每行一个整数,代表点的坐标
  以下m行 每行两个整数,代表区间的范围

4、输出格式 

输出一行,最少的满足所有区间的点数,如无解输出-1。
样例输入:
5 5
2
6
3
8
7
2 5
3 4
3 3
2 7
6 9
样例输出:
2

5、数据规模和约定 

1<=n,m<=10000
  0<=点和区间的坐标<=50000

import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;


public class xianduanhedian {
 private static InputStream is = System.in;

 public static int nextInt() {
  try {
   int i;

   while ((i = is.read()) < 45 || i > 57) {
   }

   int mark = 1, temp = 0;

   if (i == 45) {
    mark = -1;
    i = is.read();
   }

   while (i > 47 && i < 58) {
    temp = temp * 10 + i - 48;
    i = is.read();
   }

   return temp * mark;
  } catch (IOException e) {
   e.printStackTrace();
  }

  return -1;
 }

 static class Node {
  public int start;
  public int end;

  public Node(int start, int end) {
   this.start = start;
   this.end = end;
  }

 }

 public static void main(String[] args) {
  int n = nextInt();
  int m = nextInt();
  int point[] = new int[n];
  for (int i = 0; i < n; i++)
   point[i] = nextInt();
  Node node[] = new Node[m];
  for (int i = 0; i < m; i++)
   node[i] = new Node(nextInt(), nextInt());
  Arrays.sort(point);
  Arrays.sort(node, new Comparator<Node>() {
   public int compare(Node o1, Node o2) {
    return o1.end - o2.end;
   }
  });
  int currentPoint = 0;
  int count = 0;
  int j = 1;
  for (int i = 0; i < m; i++) {
   int x = node[i].start;
   int y = node[i].end;
   if (x <= currentPoint)
    continue;
   int temp = -1;
   for (j -= 1; j < n; j++) {
    if (point[j] <= y) {
     temp = point[j];
    } else {
     break;
    }
   }
   if (temp == -1) {
    count = 0;
    break;
   } else {
    currentPoint = temp;
    count++;
   }

  }
  System.out.println(count);
 }

}

以上是“Java中算法提高之线段和点的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!