单调栈,求压缩时间复杂度
查看原帖
单调栈,求压缩时间复杂度
883803
Mason123456楼主2023/12/16 16:12
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5+5;
int stk[N];// 单调递减 
int x;
int n;
int top = 0;
long long ans = 0;

int main(){
	// freopen("P1823_21.in","r",stdin);
	cin>>n;
	for(int i = 1;i <= n;i++){
		scanf("%d",&x);
		int c = -1;
		while(top > 0 && x >= stk[top]){
			if(x == stk[top] && c == -1){//当x == stk[top]时,不可能再有比stk矮的
				c = top;
			}
			ans++;
			top--;
		}
		if(top > 0)	ans++;
		if(c != -1) top = c;// 使用c标记位置,在枚举stk[top] == x后,top重新回到c的位置
		stk[++top] = x;
	}
	cout<<ans;
	return 0;
} 

另外:手写栈可能不太方便看,在这里道个歉

2023/12/16 16:12
加载中...