2021-8-11 Woodcutters
難度 1500
題目 Codeforces:
C. Woodcutters time limit per test 1 second memory limit per test 256 megabytesLittle 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 arentrees located along the road at points with coordinatesx1, x2, ..., xn. Each tree has its heighthi. 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 coordinatex
The first line contains integern(1 ≤ n ≤ 105) — the number of trees.
Nextnlines contain pairs of integersxi, hi(1 ≤ xi, hi ≤ 109) — the coordinate and the height of theі-th tree.
The pairs are given in the order of ascendingxi. No two trees are located at the point with the same coordinate.
OutputPrint a single number — the maximum number of trees that you can cut down by the given rules.
Keyword
chopper 伐木工
segment (一)段
題目解析
本題大意就是伐木工可以把樹往左砍倒或者往右砍倒,但是前提是倒下後佔據的位置沒有其他樹(包括沒有砍倒的和已經砍倒的),輸出最多能砍倒多少顆樹
簡單的貪心問題,開兩個陣列存位置和高度,然後如果與上一顆樹的間距大於樹的高度,就往左倒,如果小於等於往右倒,這時候就意味著相對於下一顆樹而言這棵樹的位置前移了樹的高度,就醬
解析完畢,以下是參考程式碼
1 #include<iostream> 2 #include<algorithm> 3 using namespace std; 4 typedef long long ll; 5 ll x[100005], h[100005]; 6 int main() 7 { 8 int n, ans = 0; cin >> n; 9 x[0] = -2e15, x[n + 1] = 2e15; 10 for (int i = 1; i <= n; i++)cin >> x[i] >> h[i]; 11 for (int i = 1; i <= n; i++) 12 { 13 if (x[i] - x[i - 1] > h[i])ans++; 14 else if (x[i + 1] - x[i] > h[i]) 15 { 16 ans++; 17 x[i]+=h[i]; 18 } 19 } 20 cout << ans << endl; 21 return 0; 22 }