怎么大家的做法都这么需要脑子?树状数组优化 DP 不是很无脑吗?
首先,把天线从左到右排序。
设 表示考虑了排序后前 个天线,覆盖了 这个区间的最小花费。
考虑在第 个天线这里花费了 个金币。设 ,那么该天线的覆盖范围就是 。接下来我们分类讨论。
- ,此时我们可以不用动前面的天线,因为该天线已经可以覆盖 这个区间了。转移:。
- ,此时我们需要前面的天线至少覆盖 ,转移:。
明显,DP 的顺序使得第 个转移中 的条件天然满足,那么只需要考虑 这个条件即可。这明显是一个后缀最小值,并且要支持单点修改,那么很容易想到树状数组。因为 很小,不用离散化,直接把后缀转为前缀即可。
时间复杂度 。
代码实现 & AC link
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define lowbit(x) (x & (-x))
const int N = 90, M = 100100;
const int inf = (int)(1e9);
template <class ty>
struct BIT {
static_assert(is_arithmetic<ty>::value, "BIT only supports arithmetic types");
private:
int sz;
vector<ty> s;
const ty inf = ((numeric_limits<ty>::max()) >> 1) - 1;
public:
BIT () : sz (0) {}
void resize (int n) { assert (n >= 0); sz = n; s.assign(sz + 1, ty(inf)); }
void modify (int x, ty d) { assert (1 <= x && x <= sz); for (int y = x; y <= sz; y += lowbit (y)) s[y] = min (s[y], d); }
ty query (int x) { assert (0 <= x && x <= sz); ty res = inf;
for (int y = x; y; y -= lowbit(y)) res = min (res, s[y]);
return res;
}
int lesseq_bound (ty x) { if (sz == 0) return 1; int p = 0; ty res = inf;
for (int i = __lg(sz); i >= 0; --i) if (int nxt = p + (1 << i); nxt <= sz && min (res, s[nxt]) > x) p = nxt, res = min (res, s[p]);
return p + 1;
}
int less_bound(ty x) { if (sz == 0) return 1; int p = 0; ty res = inf;
for (int i = __lg(sz); i >= 0; --i) if (int nxt = p + (1 << i); nxt <= sz && min (res, s[nxt]) >= x) p = nxt, res = min (res, s[p]);
return p + 1;
}
};
int n, m;
array<int, 2> a[N];
int f[N][M];
int main () {
scanf ("%d %d", &n, &m); for (int i = 1; i <= n; i++) scanf ("%d %d", &a[i][0], &a[i][1]);
sort(a + 1, a + n + 1); BIT<int> tr; tr.resize(m);
for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) f[i][j] = (int)(1e9);
for (int i = 1; i <= n; i++) { for (int j = 0; j <= m; j++) {
int l = max (1, a[i][0] - a[i][1] - j), r = min (a[i][0] + a[i][1] + j, m);
if (l == 1) f[i][r] = min (f[i][r], j);
else f[i][r] = min (f[i][r], tr.query (m + 2 - l) + j);
} for (int j = min (m, a[i][0] + a[i][1]); j <= m; j++) tr.modify (m + 1 - j, f[i][j]);
} printf ("%d\n", tr.query(1));
return 0;
}