ZOJ 1985 Largest Rectangle in a Histogram

题目地址:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1985

思路:枚举起始点O(n^3)肯定超时,O(n^2)都超时了,参考别人博客写的,用left和right数组保存比当前矩形高度高的最小下标和最大下标

待测代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int a[100010],left1[100010],right1[100010];
int main()
{
    int n;
    while(scanf("%d",&n) && n)
    {
        /*for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            left1[i] = i;
            right1[i] = i;
        }*/
        for (int i = 1; i <= n; i++)
		{
			scanf("%d", &a[i]);
			left1[i] = i;
			right1[i] = i;
		}
        /*for(int i=1; i<=n; i++)
        {
            int temp = i;
            while(temp-1>=1 && a[temp-1] >= a[i])
                temp = left1[temp-1];
            left1[i] = temp;
        }
        for(int i=n; i>=1; i--)
        {
            int temp = i;
            while(temp + 1 <= n && a[temp+1] >= a[i])
                temp = right1[temp+1];
            right1[i] = temp;
        }*/
        int i,temp;
        for (i = 1; i <= n; i++)
		{
			temp = i;
			while (temp - 1 >= 1 && a[temp - 1] >= a[i])
				temp = left1[temp - 1];
			left1[i] = temp;
		}
		for (i = n; i >= 1; i--)
		{
			temp = i;
			while (temp + 1 <= n && a[temp + 1] >= a[i])
				temp = right1[temp + 1];
			right1[i] = temp;
		}
        /*LL max1 = 0;
        for(int i=1; i<=n; i++)
        {
            LL sum = (LL)a[i] * (LL)(right1[i]-left1[i]+1);
            if(sum > max1)
                max1 = sum;
        }
        printf("%I64d\n",max1);*/
        long long max = -1, res;
		for (i = 1; i <= n; i++)
		{
			res = (long long) a[i] * (long long) (right1[i] - left1[i] + 1);
			if (res > max)
				max = res;
		}
		printf("%I64d\n",max);
    }
    return 0;
}


超时代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long LL;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int a[100010];
int main()
{
    int n;
    while(scanf("%d",&n) && n)
    {
        int max1 = 0;
        for(int i=1; i<=n; i++)
        {
            scanf("%d",&a[i]);
            int min1 = a[i];
            for(int j=i; j>=1; j--)
            {
                min1 = min(min1,a[j]);
                int sum = min1 * (i - j + 1);
                if(sum > max1)
                    max1 = sum;
            }
        }
        printf("%d\n",max1);
    }
    return 0;
}


你可能感兴趣的:(ZOJ 1985 Largest Rectangle in a Histogram)