Save the Little Ant | ||||||
| ||||||
Description | ||||||
风和日丽的一天,小八和小姐姐又约在一起拯救小蚂蚁了。因为小姐姐发现地上坑坑洼洼的一下雨就会有好多积水,会有路过的小蚂蚁掉下去被淹死...(可行性这种事,先不要考虑...) 小姐姐通过测量已经得到这条小路的海拔高度地图(测量宽度为1),现在请你帮小八计算下雨过后小路上会有多少积水? 比如: 小姐姐的地图:0 1 0 2 1 0 1 3 2 1 2 1
蓝色部分为积水,可得6。 | ||||||
Input | ||||||
有多组输入数据,每组数据先输入一个整数n(1≤n≤105),表示连续测量了n个单位水平距离的高度。接下来一行输入n个整数ai(-105≤ai≤105),按顺序给出测量的高度。 | ||||||
Output | ||||||
对于每组输入数据,输出一个数字,表示积水体积,每组输出占一行。 | ||||||
Sample Input | ||||||
12 0 1 0 2 1 0 1 3 2 1 2 1 | ||||||
Sample Output | ||||||
6
传说中的水题;
|
#include<bits/stdc++.h>
using namespace std;
int l[1000006];
int r[1000006];
int a[1000006];
int main()
{
int n;
while(scanf("%d", &n) != EOF)
{
memset(l, 0, sizeof l);
memset(r, 0, sizeof r);
for(int i = 0; i < n; i++)
scanf("%d", &a[i]);
l[0] = a[0];
r[n - 1] = a[n - 1];
for(int i = 1; i < n; i++)
l[i] = max(a[i], l[i - 1]);
for(int i = n - 2; i >= 0; i--)
r[i] = max(a[i], r[i + 1]);
long long ans = 0;
for(int i = 0; i < n; i++)
ans += max(0, min(l[i - 1], r[i + 1]) - a[i]);
printf("%lld\n", ans);
}
return 0;
}