The length of a cave is N. It tells you the height of the ground and the height of the top of each position, so that you can fill the water in it, so that the water cannot touch the ceiling (but it can be infinitely close ). The maximum amount of water. (Both sides of the cave are regarded as closed)
Idea: If you know how high a position can look to the left, and how high it can be to the right, you can know the final height of this position. The method is to scan twice. Define a previous maximum value for each scan. If the previous maximum value is higher than the current top, it is dropped to the top. If it is lower than the bottom, it will rise to the bottom (because the height behind it can be blocked by the bottom ). If it is in the middle, you do not need to change it.
Code:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define N 1000010int p[N];int s[N];int main() { int t; scanf("%d", &t); while (t--) { int n; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &p[i]); } for (int i = 0; i < n; i++) { scanf("%d", &s[i]); } int tmp = 0x3f3f3f3f; for (int i = 0; i < n; i++) { tmp = min(tmp, s[i]); tmp = max(tmp, p[i]); s[i] = tmp; } tmp = 0x3f3f3f3f; for (int i = n-1; i >= 0; i--) { tmp = min(tmp, s[i]); tmp = max(tmp, p[i]); s[i] = tmp; } int ans = 0; for (int i = 0; i < n; i++) { ans += s[i]-p[i]; } printf("%d\n", ans); } return 0;}
Va 1442: Cave (Greedy)