[lnsyoj102/luoguP2866]Bad Hair Day

题意

给定序列 \(a\),记 \(C_i\)\(a_i\) 右侧第一个 \(\ge a_i\) 的元素与 \(a_i\) 间的元素个数,求\(\sum_{i=1}^n C_i\)

sol

单调栈可以在 \(O(n)\) 的时间复杂度内解决求某个元素左(右)第一个大于(小于)的元素。
以本题为例,由于本题需要求侧第一个 \(\ge a_i\) 的元素,因此需要维护一个严格单调递减栈。从 \(n\)\(1\) 枚举,当枚举到 \(a_i\) 时,将栈顶的所有 \(< a_i\) 的元素都弹出栈,这样就可以保证栈内的元素永远严格单调递减。同时,因为所有 \(< a_i\) 的元素都已出栈,因此当前的栈顶元素就是满足上述题意的元素
注意:由于需要利用下标求 \(C_i\),因此栈内应存元素的下标而非元素的值

代码

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 80005;

int a[N];
int n;
int stk[N], top;

int main(){
	scanf("%d", &n);
	for (int i = 1; i <= n; i ++ ) scanf("%d", &a[i]);
	long long res = 0;
	stk[0] = n + 1;
	for (int i = n; i >= 1; i -- ){
		while (top && a[stk[top]] < a[i]) top -- ;
		res += stk[top] - i - 1;
		stk[ ++ top] = i;
	}
	
	printf("%lld\n", res);
	
	return 0;
}
posted @ 2024-07-20 09:56  是一只小蒟蒻呀  阅读(6)  评论(0编辑  收藏  举报