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);
		}
		
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_38970751/article/details/85332701
今日推荐