poj2796 区间和乘最小值之最大值

题目:http://poj.org/problem?id=2796

给出正整数的数组,让你求出此数组某一个区间的和乘以区间内的最小值的最大值。
例  3 1 6 4 5 2 在第3到第5个数的区间内,和为15最小值为4乘积60最大。
 

wa代码

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <stack>

using namespace std;

struct node
{
	long long i,w;
};

const long long maxSize=100000;
long long n,ans=0,l,r;
long long sum[maxSize+5],a[maxSize+5];
stack <node> s;

int main()
{
	int i;
	node n1,n2;
	
	freopen("a.txt","r",stdin);
	scanf("%lld",&n);
	sum[0]=0;
	for (i=1;i<=n;i++)
	{
		scanf("%lld",&a[i]);
		sum[i]=sum[i-1]+a[i];
	}
	
	n1.i=1;		n1.w=a[1];
	s.push(n1);
	for (i=2;i<=n;i++)	//枚举右边界 
	{
		n1=s.top();
		n2.i=i;		n2.w=a[i];
		if (n1.w<a[i])
			s.push(n2);
		else if (n1.w==a[i])
			continue;
		else
		{
			while (n1.w>a[i])
			{
				if (ans<(sum[i-1]-sum[n1.i-1])*n1.w)
				{
					ans=(sum[i-1]-sum[n1.i-1])*n1.w;
					l=n1.i;	r=i-1;
				}
				n2.i=n1.i;
				s.pop();
				if (s.empty())
					break;
				n1=s.top();
			}
			s.push(n2);
		}
	}
	while (!s.empty())
	{
		n1=s.top();	s.pop();
		if (ans<(sum[n]-sum[n1.i-1])*n1.w)
		{	
			ans=(sum[n]-sum[n1.i-1])*n1.w;
			l=n1.i;	r=n;
		}
	}
	printf("%lld\n%lld %lld",ans,l,r);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/scutbenson/article/details/81915483
今日推荐