UVA1442 Cave

题解:

从左往右扫描,初始时设水位level=s[0],然后依次判断各个位置[i,i+1]处的高度

1. 如果p[i] > level,说明水被隔绝了,需要把level提升到pi

2. 如果s[i] < level,说明水位太高,碰到天花板,需要把level降低到si

3. 位置[i,i+1]处的水位就是扫描到位置i时的level

代码

#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 100000
#define LL long long
int cas=1,T;
int p[1000005];
int s[1000005];
int h[1000005];

int main()
{
    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 level = s[0];
       for (int i = 0;i<n;i++)
       {
           if (level>s[i])
               level = s[i];
           if (level < p[i])
               level = p[i];
           h[i]=level;
       }

       level = s[n-1];
       int ans =0;
       for (int i = n-1;i>=0;i--)
       {
           if (level >s[i])
               level = s[i];
           if (level < p[i])
               level = p[i];
           ans+=min(level,h[i])-p[i];
       }
       printf("%d\n",ans);
    }
    return 0;
}

你可能感兴趣的:(UVA1442 Cave)