区间交集最值

简介: 笔记

题意


All our characters have hobbies. The same is true for Fedor. He enjoys shopping in the neighboring supermarket.


The goods in the supermarket have unique integer ids. Also, for every integer there is a product with id equal to this integer. Fedor has n discount coupons, the i-th of them can be used with products with ids ranging from li to ri, inclusive. Today Fedor wants to take exactly k coupons with him.


Fedor wants to choose the k coupons in such a way that the number of such products x that all coupons can be used with this product x is as large as possible (for better understanding, see examples). Fedor wants to save his time as well, so he asks you to choose coupons for him. Help Fedor!


Input

2.png

Output

3.png

Examples

样例 #1

4 2
1 100
40 70
120 130
125 180
31
1 2 

样例 #2


3 2
1 12
15 20
25 30


0
1 2


样例 #2


5 2
1 10
5 15
14 50
30 70
99 100


21
3 4

思路


题意:给出n个区间,求m个区间的最大覆盖,并输出覆盖的区间编号


k个区间交集 = 右端点最小值 - 左端点最大值


按区间左端点从小到大排序,用优先队列(小顶堆)维护k个右端点,保证每次选的都是最小的右端点r,用r减去这k个区间的最大l(排序后当前就是最大的l),此时求得即为被覆盖k次的区间的长度。不断进行,更新长度最大值。

int n, m;
struct node {
  int l, r;
  int id;
  bool operator<(const node &A) const {
    if (l == A.l) return r < A.r;
    return l < A.l;
  }
} a[N];
void solve() {
  cin >> n >> m;
  rep(i, 1, n) cin >> a[i].l >> a[i].r, a[i].id = i;
  sort(a + 1, a + 1 + n);
  pql q;
  int mx = 0, xx, yy;
  rep(i, 1, n) {
    q.push(a[i].r);
    if (q.sz > m) q.pop(); 
    int len = q.top() - a[i].l + 1; 
    if (q.sz == m && mx < len) {
      mx = len; 
      xx = a[i].l; 
      yy = q.top(); 
    } 
  }
  cout << mx << endl; 
  if (mx == 0) xx = 2e9, yy = -2e9; 
  for (int i = 1, j = 0; i <= n && j < m; i++) {
    if (a[i].l <= xx && a[i].r >= yy) {
      j++; 
      cout << a[i].id << ' ';
    } 
  }
}
相关文章
|
Java
[译]两个排序数组的中值
原文地址: Median of Two Sorted Arrays 有两个排序数组A和B大小分别为m和n。找到两个排序数组的中值。整个运行时复杂度应该是O(log(m + n))。
964 0
|
9月前
查询多维数组最大值或者最小值
查询多维数组最大值或者最小值
64 0
|
算法 测试技术 C++
C++算法:寻找两个正序数组的中位数
C++算法:寻找两个正序数组的中位数
|
人工智能 算法 BI
贪心算法——区间选点与最大不相交区间数
贪心算法——区间选点与最大不相交区间数
97 0
|
算法 测试技术 C#
C++前缀和算法的应用:统计中位数为 K 的子数组
C++前缀和算法的应用:统计中位数为 K 的子数组
4_寻找两个正序数组的中位数
4_寻找两个正序数组的中位数
115 0
4. 寻找两个正序数组的中位数
给定两个大小分别为 m 和 n 的正序(从小到大)数组 nums1 和 nums2。请你找出并返回这两个正序数组的 中位数 。
124 0
|
9月前
|
算法 C++
寻找两个正序数组的中位数(C++)
寻找两个正序数组的中位数(C++)
47 0
|
3月前
|
算法
正序数组中位数
给定两个有序数组nums1和nums2,要求找到它们合并后的中位数,时间复杂度需达到O(log(m+n))。通过双指针法遍历两个数组,使用left和right变量记录遍历过程中的值,最终根据合并后数组长度的奇偶性返回中位数。此方法有效避免了直接合并数组带来的高时间复杂度问题。
32 0

热门文章

最新文章