【POJ 2796】【单调栈】

一组会WA的数据-_-

10
0 0 0 0 0 0 0 0 0 0

问题转化成:对于每一个数,求出以它为最小值的最远左右端点

利用单调栈:维护栈底小,栈顶大的单调栈

                      每个数入栈的时候记录左端点(为栈中前一个数的序列位置+1)

                      出栈的时候记录右端点(为令它出栈时的数的序列位置-1)

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 300005
#define LL long long

using namespace std;

inline int wread(){
	char c(getchar ());int wans(0),flag(1);
	while (c<'0'|| c>'9'){if (c=='-') flag=-1;c=getchar ();}
	while (c>='0' && c<='9'){wans=wans*10+c-'0';c=getchar ();}
	return wans*=flag;
}

int n; 
int sav[N];
struct node{
	int zhi,pos;
	node()
	{}node(int x,int y):zhi(x),pos(y){}
}S[N];
int top;
int ml[N],mr[N];
LL sum[N];

int main (){
	n=wread();
	for (int i(1);i<=n;++i)
		sav[i] = wread();
	for (int i(1);i<=n;++i)
		sum[i] = sum[i-1]+(LL)sav[i];
	S[++top] = node(sav[1],1) ;
	ml[1]=1;
	int r(1);
	while (r!=n){
		r++;
		if (sav[r]>S[top].zhi)	ml[r]=S[top].pos+1,S[++top] = node(sav[r],r);
		else if (sav[r]==S[top].zhi)	ml[r]=ml[S[top].pos],S[++top] = node(sav[r],r);
		else {
			while (S[top].zhi>sav[r] && top>=1)	mr[S[top].pos]=r-1,top--;
			if (!top)	S[++top]=node(sav[r],r),ml[r] = 1;
			else {
				if (S[top].zhi==sav[r])	ml[r] = ml[S[top].pos],S[++top] = node(sav[r],r);
				else ml[r] = S[top].pos +1,S[++top] = node(sav[r],r);
			}
		}
	}
	while (top!=0)	mr[S[top].pos] = n,top--;
	LL ans(-1);int pr(0);
	for (int i(1);i<=n;++i)
		ans < ((LL)sav[i]*( sum[mr[i]] - sum[ml[i]-1] )) ? (pr=i,ans=((LL)sav[i]*( sum[mr[i]] - sum[ml[i]-1] ))) : ans=ans;
	printf("%lld\n",ans);
	printf("%d %d\n",ml[pr],mr[pr]);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值