紫书 例题8-18 UVa 1442 (扫描法)
从左往右扫描一遍, 得从每个位置往右伸长不会碰到天花板的高度, 右往左一样, 取最小, 然后就是可以放“水”的高度了
#include<cstdio>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;
const int MAXN = 1123456;
int p[MAXN], s[MAXN], h[MAXN], n;
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
scanf("%d", &n);
REP(i, 0, n) scanf("%d", &p[i]);
REP(i, 0, n) scanf("%d", &s[i]);
int level = s[0];
REP(i, 0, n)
{
if(p[i] > level) level = p[i];
if(s[i] < level) level = s[i];
h[i] = level;
}
int ans = 0;
level = s[n-1];
for(int i = n - 1; i >= 0; i--)
{
if(p[i] > level) level = p[i];
if(s[i] < level) level = s[i];
ans += min(level, h[i]) - p[i];
}
printf("%d\n", ans);
}
return 0;
}