BZOJ 4653: [Noi2016]区间
4653: [Noi2016]区间
Time Limit: 60 Sec Memory Limit: 256 MB
Submit: 1291 Solved: 683
[Submit][Status][Discuss]
Description
Input
Output
Sample Input
3 5
1 2
3 4
2 2
1 5
1 4
Sample Output
#include <bits/stdc++.h> using namespace std; const int maxn = 1000005; int tag[maxn << 4], val[maxn << 4], n, m; int p[maxn], tot, ans = 2e9; struct Node { int l, r, val; bool operator < (const Node &a) const { return val < a.val; } } q[maxn]; int read() { int x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();} while(ch >= '0' && ch <= '9') {x = x * 10 + ch - 48; ch = getchar();} return x * f; } void update(int o) { val[o] = max(val[o << 1], val[o << 1 | 1]); } void pushdown(int o, int l, int r) { if(tag[o] != 0) { tag[o << 1] += tag[o]; tag[o << 1 | 1] += tag[o]; val[o << 1] += tag[o]; val[o << 1 | 1] += tag[o]; tag[o] = 0; } } void Modify(int o, int l, int r, int ql, int qr, int z) { if(ql <= l && r <= qr) { tag[o] += z; val[o] += z; return; } int mid = (l + r) >> 1; pushdown(o, l, r); if(ql <= mid) Modify(o << 1, l, mid, ql, qr, z); if(qr > mid) Modify(o << 1 | 1, mid + 1, r, ql, qr, z); update(o); } int main() { n = read(); m = read(); for (int i = 1; i <= n; ++i) { q[i].l = read(); q[i].r = read(); q[i].val = q[i].r - q[i].l; p[++tot] = q[i].l; p[++tot] = q[i].r; } sort(q + 1, q + n + 1); sort(p + 1, p + tot + 1); tot = unique(p + 1, p + tot + 1) - p - 1; for (int i = 1; i <= n; ++i) { q[i].l = lower_bound(p + 1, p + tot + 1, q[i].l) - p; q[i].r = lower_bound(p + 1, p + tot + 1, q[i].r) - p; } int pos = 1; for (int i = 1; i <= n; ++i) { Modify(1, 1, tot, q[i].l, q[i].r, 1); while(val[1] >= m) { ans = min(ans, q[i].val - q[pos].val); Modify(1, 1, tot, q[pos].l, q[pos].r, -1); pos++; } } (ans == 2e9) ?printf("-1\n") :printf("%d\n", ans); return 0; }