【Data Structure and Algorithm】The problem of receiving rainwater

rainwater problem

given nn non-negative integers represent the height map of each column with a width of 1, and calculate how much rainwater the columns arranged in this way can receive after rain.

insert image description here

Problem-solving ideas: The amount of rainwater received at each location depends on the maximum height of the columns at both ends of the location. When a location ii is knowni 's column heightH i H_{i}HiAnd the maximum column height HL i HL_{i} on the left and right sides of this positionHLi H R i HR_{i} HRiAfter that, the rainwater receiving amount of this location satisfies:
V i = min ( HL i , HR i ) − H i V_{i} = min(HL_{i}, HR_{i}) - H_{i}Vi=m i n ( H Li,HRi)Hi
Then the corresponding total rainwater receiving volume VN V_{N}VNIt can be directly accumulated and calculated:
VN = ∑ i = 1 n V i V_{N} = \sum^{n}_{i=1}V_{i}VN=i=1nVi
So the key to solving the problem becomes to find the maximum column height at both ends of each position, and this problem can be solved separately by using dynamic programming to get the array HL HLH L andHR HRH R . For arrayHL HLH L ,iiThe element value of the i position represents the maximum column height existing on the left side of the position (it can be itself), for the array HR, theiiThe element value of the i position indicates the maximum column height (it can be itself) existing on the right side of the position. The specific C++ code implementation is as follows:

int trap(vector<int>& height) {
	vector<int> dpl(height.size()+1, 0); // 表示HL
	vector<int> dpr(height.size()+1, 0); // 表示HR
	dpl[0] = 0, dpr[height.size()] = 0;
	for(int i=0; i<height.size(); i++){
		dpl[i+1] = (dpl[i] > height[i] ? dpl[i] : height[i]);
	}
	for(int i=height.size()-1; i>=0; i--){
		dpr[i] = (dpr[i+1] > height[i] ? dpr[i+1] : height[i]);
	}
	int tsum = 0;
	for(int i=0; i<height.size(); i++){
		tsum += ((dpl[i+1] > dpr[i] ? dpr[i] : dpl[i+1])-height[i]);
	}
	return tsum;
}

Guess you like

Origin blog.csdn.net/zzy_NIC/article/details/121302987