51nod 1102 面积最大的矩形(单调栈)

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1102

题意:

思路:

做法就是求出每个长方形向左向右所能延伸的最大距离。

我这里用单调栈来做,维护一个单调递增的栈(自底向上递增),如果当前值大于栈顶,那么直接进栈,如果小于的话,那就说明前面比它大的那些数最多只能延伸到它这里。自己手动模拟一下就可以了。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<sstream>
 6 #include<vector>
 7 #include<stack>
 8 #include<queue>
 9 #include<cmath>
10 #include<map>
11 #include<set>
12 using namespace std;
13 typedef long long ll;
14 typedef pair<int,ll> pll;
15 const int inf = 0x3f3f3f3f;
16 const int maxn=50000+5;
17 const int mod=1e9+7;
18 
19 int n;
20 long long a[maxn];
21 stack<int> s;
22 
23 int main()
24 {
25     //freopen("in.txt","r",stdin);
26     while(~scanf("%d",&n))
27     {
28         ll ans=0;
29         while(!s.empty())  s.pop();
30         for(int i=0;i<n;i++)  scanf("%lld",&a[i]);
31         a[n]=-1;
32         for(int i=0;i<=n;i++)
33         {
34             if(s.empty()||a[i]>a[s.top()])  s.push(i);
35             else if(a[i]<a[s.top()])
36             {
37                 int tmp;
38                 while(!s.empty() && a[s.top()]>a[i])
39                 {
40                     ans=max(ans,(ll)(i-s.top())*a[s.top()]);
41                     tmp=s.top();
42                     s.pop();
43                 }
44                 s.push(tmp);
45                 a[tmp]=a[i];
46             }
47         }
48         printf("%lld
",ans);
49     }
50     return 0;
51 }
原文地址:https://www.cnblogs.com/zyb993963526/p/7395534.html