Purple Book Example 8-18 UVa 1442 (Scanning Method)

Scan from left to right, you have to extend from each position to the right without touching the height of the ceiling, the same from right to left, take the smallest, and then the height where you can put "water"

#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;

intmain()
{
	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 years = 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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325949984&siteId=291194637