Interval Coverage

本文深入探讨了区间覆盖问题,提供了一种高效的贪心算法解决方案。通过排序和扫描,选取最少数量的区间覆盖指定范围,详细解析了算法流程及其实现细节。

Interval Coverage

描述

You are given N intervals [S1, T1], [S2, T2], [S3, T3], ... [SN, TN] and a range [X, Y]. Select minimum number of intervals to cover range [X, Y].

输入

The first line contains 3 integers N, X and Y. (1 <= N <= 100000, 1 <= X < Y <= 1000000)

The following N lines each contain 2 integers Si, Ti denoting an interval. (1 <= Si < Ti <= 1000000)

输出

Output the minimum number of intevals to cover range [X, Y] or -1 if it is impossible.

样例输入

5 1 5
1 2    
1 3  
2 4  
3 5  
4 5 

样例输出

2

 

首先找到一个起点 <= X,并且终点尽量大(靠右)的区间,选为第一个区间。不妨设这个区间的终点是R[1]。

然后再找一个起点 <= R[1],并且终点尽量大的区间,选为第二个区间。不妨设这个区间的终点是R[2]。

重复以上步骤,直到某个R[k]满足R[k] >= Y,这时R[1] ... R[k]即是一组最优的区间,k即是答案。

如果在中间某一步发现R[k] == R[k-1],说明做不到覆盖整个[X, Y],输出-1。

以上贪心算法最关键的就是找起点 <= 某个值,同时终点尽量大的区间。

我们可以将所有区间按起点排序,然后从头到尾扫描即可完成以上的查找。复杂度是排序O(NlogN) + 扫描贪心O(N)。

 

 

import java.util.*;
public class Main{
	static class Inteval{
		int s;
		int e;
		Inteval(int s, int e) {
			this.s = s;
			this.e = e;
		}
	}
	public static void main(String[] args){
		Scanner sc = new Scanner(System.in);

		int n = sc.nextInt();
		int x = sc.nextInt();
		int y = sc.nextInt();
		Inteval[] arr = new Inteval[n];
		for (int i = 0; i < n; i++)
		{
			arr[i] = new Inteval(sc.nextInt(), sc.nextInt());
		}

		Arrays.sort(arr, new Comparator<Inteval>() {
            @Override
            public int compare(Inteval o1, Inteval o2) {
				if (o1.s < o2.s || o1.s == o2.s && o1.e < o2.e) {
					return -1;
				} else {
					return 1;
				}
			}
      	});
		
		int tmp = 0;
		int ans = 0;
		for (int i = 0; i < n; i++) {
			if (arr[i].e <= x) {
				continue;
			}

			if (arr[i].s >= y) {
				break;
			}

			if (arr[i].s <= x) {
				if (arr[i].e > tmp) {
					tmp = arr[i].e;
				}
			} else {
				ans++;
				if (tmp >= y) {
					System.out.println(ans);
					return;
				} else if (tmp <= x || arr[i].s > tmp) {
					System.out.println(-1);	
					return;
				} else {
					x = tmp;
					tmp = arr[i].e;
				}
			}
		}
		if (tmp < y){
			System.out.println(-1);	
		} else {
			System.out.println(ans + 1);
		}
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值