单调栈-POJ 2796 Feel Good

POJ 2796 Feel Good

题目意思: \(\displaystyle \sum^j_{y=i}X_y, (1 \leq i\leq j \leq N)* min(X_{i}|1 \leq i \leq N)\)

PS:这题要多组读入,C++ cout cin记得优化

#include <iostream>
#include <stack>
using namespace std;
typedef long long int ll;

const int MAXN = 1e6 + 7;
ll height[MAXN],sum[MAXN];
int Left,Right;
int n;

ll solve(){
	ll ans = 0;
	stack<int> s;
	height[n+1] = -1;
	Left = Right = 1;
	for(int i=1;i<=n+1;i++){
		while(!s.empty() && height[s.top()] > height[i]){
			int cur = s.top();
			s.pop();
			int _left = (s.empty()?1:s.top()+1);
			int _right = i-1;
			ll tmp = height[cur]*(sum[_right]-sum[_left-1]);
			if(tmp > ans){
				ans = tmp;
				Left = _left;
				Right = _right;
			}
		}
		s.push(i);
	}
	return ans;
}

int main(){
	while(~scanf("%d",&n)){
		sum[0] = 0;
		for(int i=1;i<=n;i++) {
			scanf("%lld",&height[i]);
			sum[i] = sum[i-1] + height[i];
		}
		printf("%lld\n",solve());
		printf("%d %d\n",Left,Right);	
	}
	return 0;
}
posted @ 2019-07-24 17:05  zz2108828  阅读(177)  评论(0编辑  收藏  举报