Untitled

 avatar
ducsieumanh1hitlanamguku
plain_text
12 days ago
724 B
3
Indexable
Never
#include<bits/stdc++.h>
using namespace std;
int n,a[1000005],r[1000005],l[1000005];
stack <int> mmb = stack <int> ();
void add(int i) {
	while (a[i]>=a[mmb.top()]) {
		r[mmb.top()]=i;
		mmb.pop();
	}
	if (!mmb.empty()) {
		l[i]=mmb.top();
	}
	mmb.push(i);
}
int main() {
	cin>>n ;
	for (int i=1;i<=n;i++) {
		cin>>a[i];
	}
	a[0]=1e9+1;
	mmb.push(0);
	for (int i=1;i<=n;i++) {
		add(i);
	}
	long long tong=0;
	for (int i=1;i<=n;i++) {
		if (a[l[i]]>a[r[i]]&&l[i]!=0&&r[i]!=0) {
			tong+=a[r[i]];
		} else if (a[l[i]]<a[r[i]]&&l[i]!=0&&r[i]!=0) {
			tong+=a[l[i]];
		} else if (l[i]!=0&&r[i]==0) {
			tong+=a[l[i]];
		} else if (l[i]==0&&r[i]!=0) {
			tong+=a[r[i]];
		}
	}
	cout<<tong;
}
Leave a Comment