区间交集最值

简介: 笔记

题意


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 << ' ';
    } 
  }
}
相关文章
|
3天前
|
机器学习/深度学习 算法 测试技术
【线段树】【区间更新】2916. 子数组不同元素数目的平方和 II
【线段树】【区间更新】2916. 子数组不同元素数目的平方和 II
【线段树】【区间更新】2916. 子数组不同元素数目的平方和 II
|
3天前
|
算法 C++
寻找两个正序数组的中位数(C++)
寻找两个正序数组的中位数(C++)
14 0
|
3天前
|
C++
汇总区间(C++)
汇总区间(C++)
24 0
|
3天前
|
算法 安全 C#
Leetcode算法系列| 4. 寻找两个正序数组的中位数
Leetcode算法系列| 4. 寻找两个正序数组的中位数
|
5月前
|
算法 测试技术 C#
C++二分查找算法:有序矩阵中的第 k 个最小数组和(二)
C++二分查找算法:有序矩阵中的第 k 个最小数组和
|
5月前
|
算法 测试技术 C++
C++二分查找算法:有序矩阵中的第 k 个最小数组和(一)
C++二分查找算法:有序矩阵中的第 k 个最小数组和
|
5月前
|
算法 测试技术 C#
C++ 算法:区间和的个数
C++ 算法:区间和的个数
|
7月前
|
算法 测试技术 C++
C++算法:寻找两个正序数组的中位数
C++算法:寻找两个正序数组的中位数
|
10月前
|
算法
寻找两个正序数组中的中位数
寻找两个正序数组中的中位数
|
12月前
7-234 两个有序序列的中位数
7-234 两个有序序列的中位数
82 0