hdu 1506 并查集的思想

就是利用rig和lef数组记录左边连续的比自身高的最远位置,然后统计,每次只要找到一个中断点则查询结束,避免了重复运算,最坏复杂度是n^2但平均复杂度,但对于一般的数据还是有很优秀的复杂度的

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 100007

using namespace std;

typedef long long LL;

LL h[MAX];
LL rig[MAX];
LL lef[MAX];

int main ( )
{
    int n;
    while ( ~scanf ( "%d" , &n ),n )
    {
        for ( int i = 1 ; i <= n ; i++ )
        {
            scanf ( "%lld" , &h[i] );
            lef[i] = i;
            rig[i] = i;
        }
        for ( int i = 2 ; i <= n ; i++ )
            while ( lef[i] > 1 && h[lef[i]-1] >=h[i] )
                lef[i] = lef[lef[i]-1];
        for ( int i = n-1 ; i >= 1 ; i-- )
           while ( rig[i] < n && h[rig[i]+1] >= h[i] )
               rig[i] = rig[rig[i]+1];
        LL ans = 0;
        for ( int i = 1 ; i <= n ; i++ )
            ans = max ( ans , ( rig[i] - lef[i] + 1 )*h[i] );
        printf ( "%I64d\n" , ans );
    }
}


你可能感兴趣的:(C++,动态规划)