蓝桥 线段和点(Java)

这篇博客探讨了一个计算机科学中的经典问题——区间覆盖。给定一定数量的点和区间,目标是最小化满足所有区间的点的数量。文章通过一个样例解释了问题的输入输出格式,并展示了一个Java解决方案,该方案首先对点和区间进行排序,然后使用贪心策略找到满足条件的最少点数。算法的关键在于排序和遍历过程,有效地减少了所需点的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

AILAB专项训练

问题描述

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

输入格式

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

输出格式

输出一行,最少的满足所有区间的点数,如无解输出-1。

样例输入

5 5
2
6
3
8
7
2 5
3 4
3 3
2 7
6 9

样例输出

2

数据规模和约定

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

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


public class Main {
	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);
	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Abdulaziz02

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值