问题
假设水滴长宽都是1,柱子宽是1,那么给了这个柱子的二维高度图后,在下雨后,柱子间能容纳多少水滴
例如:1代表柱,0代表水滴
1 | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
1 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | ||||
1 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
其高度列为0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1
结果为 6
1 | |||||
---|---|---|---|---|---|
1 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 0 | 1 | 0 | 1 |
1 | 1 | 0 | 1 | 1 | 1 |
1 | 1 | 0 | 1 | 1 | 1 |
4, 2, 0, 3, 2, 5
结果为 9
代码
这里采用求出最大柱子高度后,每一高度扫描所有列的方法解
void col_water2(const int* heights, const int count) {
int max_height = 0;
for (int i = 0; i < count; ++i) {
if (max_height < heights[i]) {
max_height = heights[i];
}
}
int total_water = 0;
for (int i = 0; i < max_height; ++i) {
int begin_index = -1;
for (int j = 0; j < count; ++j) {
if (begin_index == -1) {
// 左边未封
if (heights[j] > i) {
// 找到左边的墙
begin_index = j;
}
}else {
if (heights[j] > i) {
// 找到右边的墙
total_water += j - begin_index - 1;
begin_index = j;
}
}
}
}
for (int row = max_height; row > 0; --row) {
for (int col = 0; col < count; ++col) {
std::cout << "|" << (row <= heights[col] ? "1" : " ");
}
std::cout << "|";
std::cout << std::endl;
if (row == max_height) {
for (int col = 0; col < count; ++col) {
std::cout << "|:--:";
}
std::cout << "|";
std::cout << std::endl;
}
}
std::cout << std::endl << "RESULT: " << total_water <<std::endl;
}
int main() {
const int heights[] = {
0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1
};
const int heights2[] = {
4, 2, 0, 3, 2, 5
};
//col_water(heights, sizeof(heights) / sizeof(int));
std::cout << std::endl;
col_water2(heights, sizeof(heights) / sizeof(int));
col_water2(heights2, sizeof(heights2) / sizeof(int));
return 0;
}