单调栈
什么是单调栈?
单调栈 满足了栈的性质(先进后出) , 但对数据来说, 保存的数据是严格单调递增的(递减的)。
单调栈的性质:
正因为保存的数据时严格单调的,对于1 4 5 7 2 来说 只能保存 1 2 而 4 5 7 不能被保存,从而确定了 4 5 7 的左右边界, 1 为 左边界, 2 为右边界。
所以:一旦一个元素已经进入栈中那么这个元素向左扩展的位置就确定下来了.(对于4 来说 左边界(左扩充的位置) 为1)
一旦一个元素出栈被弹出栈,那么这个元素向右扩展的位置也确定下来了.(对于4 来说 右边界(右扩充的位置) 为2)
单调栈应用:题目: http://acm.hdu.edu.cn/showproblem.php?pid=1506
详细解释 “: http://www.cnblogs.com/legendmaner/archive/2013/04/18/3028748.html
代码:
#include<stdio.h>
#include<stack>
#include<stdint.h>
using namespace std;
#define MAX(a,b) a >= b ? a:b
struct node{
int64_t data ;
int step ;
int start;
};
stack<struct node> S;
int64_t FindMax(long long max,struct node num)
{
while(!S.empty()&&S.top().data>=num.data)
{
max=MAX(max,(num.step-S.top().start)*S.top().data);
S.pop();
}
if(S.empty())
{
num.start = 1;
S.push(num);
}
else
{
num.start = S.top().step+1;
S.push(num);
}
return max;
}
int main (void)
{
int N;
while(~scanf("%d",&N),N)
{
struct node num;
int64_t max=0;
for(int i=1; i<=N; i++)
{
scanf("%I64d",&num.data);
num.step=i;
max=FindMax(max,num);
}
while(!S.empty())
{
max=MAX(max,(N+1-S.top().start)*S.top().data);
S.pop();
}
printf("%I64d\n",max);
}
return 0;
}
值得注意的是 时 max 的范围 用int64_t保存
可以用 9 1000000000 1000000000 1000000000 1000000000 1000000000 1000000000 999999999 1000000000 1000000000 来检测