跳到正文

题解

题解 P2422 【良好的感觉】

Treaker约 2 分钟
原文
文章信息与版本

文章信息

发布
2019年9月23日
收录
2025年12月12日
更新
2026年11月20日
篇幅
约 2 分钟
获赞
32
题目
P2422

版本

  1. v1当前
Treaker\color{cornflowerblue}{\mathcal{Treaker}}

单调栈 + 前缀和

搞不懂标签为什么是DP 和 单调队列 -.-

我们发现感受值全是正数,也就是说前缀和是单调递增,当最小值不变时,区间越长越优。

那么我们再考虑,如何求一个区间的最小值呢?

换个角度,我们考虑一个值它能作为什么区间的最小值,即它能向两边扩展多少。

那么问题就很显然了,我们维护一个单调递减的栈,正反分别跑一遍,就能求出左右边界,在统计答案即可。。。

完整代码如下:

C++
#include <cstdio>
#include <iostream>
using namespace std;
const int N = 100005;
inline int read()
{
	int x = 0 , f = 1;	char ch = getchar();
	while(ch < '0' || ch > '9')	{if(ch == '-')	f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') {x = (x << 3) + (x << 1) + (ch ^ 48); ch = getchar();}
	return x * f;
}
int n , top;
int a[N] , st[N] , l[N] , r[N];
long long sum[N];
long long ans;
int main()
{
	n = read();
	for(int i = 1;i <= n;i ++)	sum[i] = sum[i-1] + (a[i] = read());
	for(int i = 1;i <= n;i ++)
	{
		while(top && a[st[top]] >= a[i]) top --;
		l[i] = st[top];
		st[++top] = i;
	}
	top = 0;
	st[0] = n+1;
	for(int i = n;i >= 1;i --)
	{
		while(top && a[st[top]] >= a[i]) top --;
		r[i] = st[top] - 1;
		st[++top] = i;
 	}
 	for(int i = 1;i <= n;i ++)	ans = max(ans,(sum[r[i]] - sum[l[i]]) * a[i]);
 	return printf("%lld\n",ans) , 0;
}