1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
| #include<bits/stdc++.h> const int N = 5e5 + 10; using namespace std; #define ll long long int n, m; struct U { ll l, r; ll length; bool operator < (U o) const { return length < o.length; } } segment[N]; ll b[N << 1], btop; ll c[N << 1], ctop;
struct Seg { #define ls (u << 1) #define rs ((u << 1) | 1) int tree[N << 4]; int tag[N << 4]; void pushup(int u) { tree[u] = max(tree[ls], tree[rs]); } void pushdown(int u, int l, int r) { int mid = (l + r) >> 1; tree[ls] += tag[u]; tree[rs] += tag[u]; tag[ls] += tag[u], tag[rs] += tag[u]; tag[u] = 0; } void change(int u, int l, int r, int L, int R, int val) { if(L <= l && r <= R) { tree[u] += val; tag[u] += val; return; } pushdown(u, l, r); int mid = (l + r) >> 1; if(L <= mid) change(ls, l, mid, L, R, val); if(R > mid) change(rs, mid + 1, r, L, R, val); pushup(u); } int query() {
return tree[1]; } }sgtree;
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0); cin >> n >> m; for(int i = 1;i <= n;i++) { cin >> segment[i].l >> segment[i].r; segment[i].length = segment[i].r - segment[i].l; b[++btop] = segment[i].l, b[++btop] = segment[i].r; } b[0] = -1; sort(b + 1, b + 1 + btop); for(int i = 1;i <= btop;i++) { if(b[i] != b[i - 1]) c[++ctop] = b[i]; } for(int i = 1;i <= n;i++) { segment[i].l = lower_bound(c + 1, c + 1 + ctop, segment[i].l) - c; segment[i].r = lower_bound(c + 1, c + 1 + ctop, segment[i].r) - c; } sort(segment + 1, segment + 1 + n); int l = 1, r = 1; ll ans = 1145141919810; for(int r = 1;r <= n;r++) {
sgtree.change(1, 1, ctop, segment[r].l, segment[r].r, 1);
while(sgtree.query() >= m) { ans = min(ans, segment[r].length - segment[l].length); sgtree.change(1, 1, ctop, segment[l].l, segment[l].r, -1); l++; } } if(ans == 1145141919810) { printf("-1"); return 0; } else { cout << ans << endl; } return 0; }
|