题目大意
Little Susie listens to fairy tales before bed every day. Today’s fairy tale was about wood cutters and the little girl immediately started imagining the choppers cutting wood. She imagined the situation that is described below.
There are n trees located along the road at points with coordinates x1, x2, …, xn. Each tree has its height hi. Woodcutters can cut down a tree and fell it to the left or to the right. After that it occupies one of the segments [xi - hi, xi] or [xi;xi + hi]. The tree that is not cut down occupies a single point with coordinate xi. Woodcutters can fell a tree if the segment to be occupied by the fallen tree doesn’t contain any occupied point. The woodcutters want to process as many trees as possible, so Susie wonders, what is the maximum number of trees to fell.
题目链接
分析
虽然题目打着dp的标签,但是用贪心是完全可行的。第一棵树可以向左倒,最后一棵树可以向右倒。我们从左到右遍历一下模拟砍树的过程,让树优先向右边倒(这样不会影响下一棵树能否砍下),如果可以就砍倒,否则再去判断是否可以向右倒,注意向右倒时要更新一下坐标。这样,对于砍过的树,我们就不用管它了,然后继续看下一棵。
代码
应该是相当简洁了
#include <cstdio>
using namespace std;
const int N = 1e5 + 10;
const long long INF = 2e15;
int n;
long long x[N], h[N];
int main() {
scanf("%d", &n);
int ans = 0;
x[0] = -INF, x[n + 1] = INF;
for (int i = 1; i <= n; ++i) {
scanf("%lld%lld", &x[i], &h[i]);
}
for (int i = 1; i <= n; ++i) {
if (x[i] - x[i - 1] > h[i])
++ans;
else if (x[i + 1] - x[i] > h[i]){
++ans;
x[i] += h[i];
}
}
printf("%d\n", ans);
return 0;
}