本文共 1689 字,大约阅读时间需要 5 分钟。
为了解决这个问题,我们需要找到数轴上最多的不相交区间。我们可以使用贪心算法来解决这个问题,这种算法通常能找到最优解,尤其是在区间调度问题中。
import java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Arrays;public class Main { static int n = 0, N = 100010; public static void main(String[] args) throws Exception { BufferedReader buf = new BufferedReader(new InputStreamReader(System.in)); n = Integer.valueOf(buf.readLine()); int[][] nums = new int[n][2]; int t = 0; while (n-- != 0) { String[] info = buf.readLine().split(" "); int a = Integer.valueOf(info[0]); int b = Integer.valueOf(info[1]); nums[t][0] = a; nums[t][1] = b; t++; } Arrays.sort(nums, (a, b) -> { if (a[0] != b[0]) { return Integer.compare(a[0], b[0]); } else { return Integer.compare(b[1], a[1]); } }); int right = -Integer.MAX_VALUE; int cnt = 0; for (int i = 0; i < nums.length; i++) { if (nums[i][0] > right) { cnt++; right = nums[i][1]; } } System.out.print(cnt); }} BufferedReader 读取输入数据,解析区间端点。这种方法确保了我们总是选择最优的区间,从而得到最多的不相交区间数量。
转载地址:http://vyre.baihongyu.com/