SP10622 DIFERENC - DIFERENCIJA 题解

题目传送

思路:

单调栈维护 4 4 4 个值:令当前数为 i i i , 维护 i i i 往前第一个大于/小于 a i ai ai 的数的位置和 i i i 往后第一个大于/小于 a i ai ai的数的位置 ,枚举每一个数的贡献即可,注意一下去重的细节(可以规定做出贡献的最小值为所有相同的最小数中位于区间最左侧的,最大值同理)。

Code:

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int MX=300005;
int n,le_cnt[MX],array[MX];ll tot;struct STR{int pos,num;};stack<STR>stk;
STR pack(int pos,int num){STR a;a.pos=pos;a.num=num;return a;}
void stk_push1(){
	for(int i=1;i<=n;i++){
		while(!stk.empty()&&stk.top().num<array[i]){
		    tot+=(ll)(array[stk.top().pos])*(ll)(i-stk.top().pos)*(ll)(le_cnt[stk.top().pos]+1);stk.pop();
	    }
		le_cnt[i]=i-(stk.empty()?1:stk.top().pos+1);stk.push(pack(i,array[i]));
	}
	while(!stk.empty()){
		tot+=(ll)(array[stk.top().pos])*(ll)(n-stk.top().pos+1)*(ll)(le_cnt[stk.top().pos]+1);stk.pop();
	}
}
void stk_push2(){
	for(int i=1;i<=n;i++){
		while(!stk.empty()&&stk.top().num>array[i]){
		    tot-=(ll)(array[stk.top().pos])*(ll)(i-stk.top().pos)*(ll)(le_cnt[stk.top().pos]+1);stk.pop();
	    }
		le_cnt[i]=i-(stk.empty()?1:stk.top().pos+1);stk.push(pack(i,array[i]));
	}
	while(!stk.empty()){
		tot-=(ll)(array[stk.top().pos])*(ll)(n-stk.top().pos+1)*(ll)(le_cnt[stk.top().pos]+1);stk.pop();
	}
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&array[i]);
	stk_push1();stk_push2();printf("%lld",tot);
	return 0;
}
  • 8
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值