-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_1326_minTaps.cc
65 lines (59 loc) · 1.31 KB
/
Problem_1326_minTaps.cc
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
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Solution
{
public:
int minTaps(int n, vector<int>& ranges)
{
vector<int> right_most(n + 1);
for (int i = 0; i <= n; ++i)
{
int r = ranges[i];
if (i > r)
{
right_most[i - r] = i + r; // 对于 i-r 来说,i+r 必然是它目前的最大值
}
else
{
right_most[0] = std::max(right_most[0], i + r);
}
}
int ans = 0;
int cur_right = 0; // 已建造的桥的右端点
int next_right = 0; // 下一座桥的右端点的最大值
for (int i = 0; i < n; ++i)
{
// 注意这里没有遍历到 n,因为它已经是终点了
next_right = std::max(next_right, right_most[i]);
if (i == cur_right)
{
// 到达已建造的桥的右端点
if (i == next_right)
{
// 无论怎么造桥,都无法从 i 到 i+1
return -1;
}
// 造一座桥
cur_right = next_right;
++ans;
}
}
return ans;
}
};
void testMinTaps()
{
Solution s;
vector<int> r1 = {3, 4, 1, 1, 0, 0};
vector<int> r2 = {0, 0, 0, 0};
EXPECT_EQ_INT(1, s.minTaps(5, r1));
EXPECT_EQ_INT(-1, s.minTaps(3, r2));
EXPECT_SUMMARY;
}
int main()
{
testMinTaps();
return 0;
}