zoukankan      html  css  js  c++  java
  • POJ 2559

    http://poj.org/problem?id=2559

    题意:就是找出可以完整连接的最大的矩形面积。

    思路:找出单独的一块矩形,往两边延伸,记录两边的比他高的矩形是在哪个位置,然后最右的位置减去最左边的矩形的位置。就是这个矩形最大可构成的面积。

    但是,如果一个一个用循环去做的话,结果是必定超时的,所以这里要用到单调栈。

    比如找出最左边的比目标矩形要高的矩形的位置的代码

     1      while(!s.empty())    //对栈首先进行清空。
     2 
     3             s.pop();  
     4 
     5         s.push(0);     //入栈一个边界位置。
     6 
     7         for(int i=1;i<=n;i++){
     8  
     9             for(x=s.top();a[x]>=a[i];x=s.top())   //如果a[x]要比那个a[i]
    也就是目标矩形要大的话,那么说明可以继续往左寻找。如果没有比目标矩形要大的话,那么这个就是
    它的右边那个就是最临界的那个矩形。
    10 s.pop(); 11 12 l[i]=x+1; 13 14 s.push(i); 15 }
     1 #include <stdio.h>
     2 #include <iostream>
     3 #include <stack>
     4 
     5 #define X 1000010
     6 
     7 using namespace std;
     8 
     9 stack<int >s;
    10 int n,x;
    11 long long a[X],m,ans,r[X],l[X];
    12 int main()
    13 {
    14   //  freopen("in.txt","r",stdin);
    15     while(scanf("%d",&n),n!=0){
    16         ans=0;
    17         a[0]=-1;a[n+1]=-1;
    18         for(int i=1;i<=n;i++)
    19             scanf("%lld",&a[i]);
    20         while(!s.empty())
    21             s.pop();  s.push(0);
    22         for(int i=1;i<=n;i++){
    23             for(x=s.top();a[x]>=a[i];x=s.top())
    24                 s.pop();
    25                 l[i]=x+1;
    26                 s.push(i);
    27             }
    28         while(!s.empty())
    29             s.pop();s.push(n+1);
    30         for(int i=n;i>0;i--){
    31             for(x=s.top();a[x]>=a[i];x=s.top())
    32                 s.pop();
    33                 r[i]=x-1;
    34                 s.push(i);
    35                 if((r[i]-l[i]+1)*a[i]>ans) ans=(r[i]-l[i]+1)*a[i];
    36             }
    37         printf("%lld
    ",ans);
    38     }
    39     return 0;
    40 }
  • 相关阅读:
    PHP伪造referer访问地址
    第一个伪静态(url重写)测试
    url重写(伪静态)IIS配置图解
    两个DropDownList数据绑定联动(数据库)
    PlaceHolder
    Page之IsPostBack属性
    确定删除吗?
    很喜欢的一个组合 因为他们的音乐改变了我对许多事物的看法SAVAGE GARDEN
    DragonBones 骨骼动画引擎
    关于Flash的Sockt通信与跨域文件
  • 原文地址:https://www.cnblogs.com/Tree-dream/p/5701137.html
Copyright © 2011-2022 走看看