单调栈poj2796

利用单调栈可以得到一个区间最小的数为lib[ k ]时,该区间的左边界与右边界,从而得到最大的值作为结果


//#include 
#include 
#include 
#include 

#include 
#include 
#include 

#include 

#define MAX(a, b) (a > b ? a : b)
#define MIN(a, b) (a < b ? a : b)
using namespace std;
typedef long long int ll;
const double eps = 1e-8;
const int MAXN = 1e5 + 5;
const int INF = 0x7fffffff;

stack< int > sta;

int lib[MAXN];
ll sum[MAXN];

void solve()
{
	int n, k;
	while( cin >> n)
	{
		int r(1), l(1);
		ll ans = 0;
		while( !sta.empty())
			sta.pop();

		*lib = *sum = 0;
		for(int i = 1; i <= n; ++i)
		{
			scanf("%d", lib + i);
			sum[i] = sum[i - 1] + lib[i];
		}
		bool flag = true;
		k = 1;
		sta.push(0);

		for(int i = 1; i <= n; ++i)
		{
			while( sta.size() > 1 && lib[i] <= lib[ sta.top() ])
			{
				k = sta.top();
				sta.pop();
				//printf("%d %d %d %lld\n", k, i, sta.top(), ans);
				if(ans < lib[k] * (sum[ i - 1] - sum[ sta.top()]))
				{
					r = i - 1;
					l = sta.top() + 1;
					ans = lib[k] * (sum[ i - 1] - sum[ sta.top()]);
				}
			}
			sta.push( i );
		}

		n = sta.top();
		while( sta.size() > 1)
		{
			k = sta.top();
			sta.pop();
			if( ans < lib[k] * (sum[ n ] - sum[ sta.top()]))
			{
					r = n;
					l = sta.top() + 1;
					ans = lib[k] * (sum[ n ] - sum[ sta.top() ]);
			}
		}

		printf("%lld\n%d %d\n", ans, l, r);
	}
}


int main()
{
	solve();
	return 0;
}


你可能感兴趣的:(algorithm_单调栈)