dut1305 台阶

Description

如上图所示的一个台阶他的积水量是4 + 2 + 4 + 3 + 4 = 17.

给你一个长度是n的台阶。告诉你每个台阶的高度,求积水量是多少?

Input

多组输入数据:

每组数据第一行一个整数n(1 <= n <= 100 000).

第二行n个整数,其中ai是第i个数。(0 <= ai <= 10 000)

Output

每组数据输出一行表示台阶的积水量。

Sample Input

10 2 5 1 3 1 2 1 7 7 6

Sample Output

17

 

想我大二的时候就左思右想不会做这道题。。。大三了觉得再做不出来太丢人。。。于是苦思冥想。。。。

开始的思路总是想从左到右扫一遍。。考虑各种情况总是有漏洞。。比如 5 2 3 1 2这种。。

卡在一个思路好久,奈何找不到题解。。。提问没人解答。。。

后来想到排序,然后从高到矮依次处理。如果该数在已处理的区间内那么就不用再考虑的,否则把该数位置到区间的中间填满,然后扩大已处理的区间。。

还是水题啊。。不过终于做出来好开心 ^_^

#include <iostream>
#include <algorithm>
#include <cstdio>

using namespace std;

typedef long long ll;

const int N = 100005;

struct node {
    int val;
    int pos;
    bool operator < (node a) const
    {
        return val > a.val;
    }
} a[N];

int b[N];

int main()
{
    int n;
    while (cin >> n)
    {
        for (int i = 0; i < n; ++i)
        {
            cin >> a[i].val;
            a[i].pos = i;
            b[i] = a[i].val;
        }
        sort(a, a + n);
        int l, r;
        l = r = a[0].pos;
        ll ans = 0;
        for (int i = 1; i < n; ++i)
        {
            //printf("%d %d %d
", i, l, r);
            //printf("%d %d
", a[i].pos, a[i].val);
            if (a[i].pos < r && a[i].pos > l) continue;
            if (a[i].pos < l)
            {
                for (int j = a[i].pos + 1; j < l; ++j)
                {
                    ans += a[i].val - b[j];
                    //cout << ans << endl;
                }
                l = a[i].pos;
            }
            else if (a[i].pos > r)
            {
                for (int j = r + 1; j < a[i].pos; ++j)
                    ans += a[i].val - b[j];
                r = a[i].pos;
            }
        }
        cout << ans << endl;
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/wenruo/p/4955472.html