-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathq17.21.cpp
106 lines (80 loc) · 2.25 KB
/
q17.21.cpp
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
#include <pair>
#include <queue>
#include <utility> // make_pair
#include <vector>
using namespace std;
/* SMALL CHANGE: MUSTE INCLUDE PREPROCESSING STEP TO REDUCE TIME COMPLEXITY */
typedef vector<int>::iterator ITER;
ITER find_iter_next_max(ITER first, ITER last) {
ITER iter_next_max = first + 1;
while (true) {
first++;
if (*first > *iter_next_max)
iter_next_max = first;
if (first == last)
break;
}
return iter_next_max;
}
void update_vol_helper(ITER first, ITER last, int &volume) {
volume += min(*first, *last) * (last - first - 1);
// subtracts volume of intermediate lower hist peaks
first++;
while (first != last) {
volume -= *first;
first++;
}
return;
}
void update_volume(ITER iter_first, ITER iter_last, ITER iter_next_max,
int &volume) {
if ((*iter_last >= *iter_first) || (iter_next_max == iter_last)) {
update_vol_helper(iter_first, iter_last, volume);
}
else {
while (true) {
update_vol_helper(iter_first, iter_next_max, volume);
if (iter_next_max == iter_last)
break;
iter_first = iter_next_max;
iter_next_max = find_iter_next_max(iter_next_max, iter_last);
}
}
return;
}
int find_hist_vol(vector<int> &input) {
ITER iter_first, iter_next_max, iter_last;
iter_first = input.begin();
iter_next_max = input.begin() + 1;
iter_last = input.begin() + 1;
int volume = 0;
while (true) {
if (iter_last == input.end()) {
update_volume(iter_first, iter_last--, iter_next_max, volume);
break;
}
if (*iter_last == 0) {
iter_last++;
continue;
}
if (*iter_last >= *iter_first) {
update_volume(iter_first, iter_last, iter_next_max, volume, input);
iter_first = iter_last;
iter_last++;
iter_next_max = iter_last;
continue;
}
if (*iter_last > *iter_next_max)
iter_next_max = iter_last;
iter_last++;
}
return volume;
}
int main(void) {
vector<int> input{0, 0, 4, 0, 0, 6, 0, 0, 3, 0, 5, 0, 1, 0, 0};
// vector<int> input{1, 0, 1};
int vol = find_hist_vol(input);
cout << "volume is: " << vol << endl;
return 0;
}