求助0pts,样例输出18
查看原帖
求助0pts,样例输出18
941575
Stars_visitor_tyw楼主2024/1/12 14:56
#include<bits/stdc++.h>
using namespace std;
int ansl1[1000005], ansr1[1000005], n, a[1000005], ansl2[1000005], ansr2[1000005];

void upr1()
{
	stack<int> stk;
	stk.push(n+1);
	for(int i=1;i<=n;i++)
	{
		while(!stk.empty()&&a[stk.top()]>=a[i])
		{
			ansr1[stk.top()]=i;
			stk.pop();
		}
		stk.push(i);
	}
}
void upl1()
{
	stack<int> stk;
	stk.push(0);
	for(int i=n;i>=1;i--)
	{
		while(!stk.empty()&&a[stk.top()]>=a[i])
		{
			ansl1[stk.top()]=i;
			stk.pop();
		}
		stk.push(i);
	}
}
void upr2()
{
	stack<int> stk;
	stk.push(n+1);
	for(int i=1;i<=n;i++)
	{
		while(!stk.empty()&&a[stk.top()]<a[i])
		{
			ansr2[stk.top()]=i;
			stk.pop();
		}
		stk.push(i);
	}
}
void upl2()
{
	stack<int> stk;
	stk.push(0);
	for(int i=n;i>=1;i--)
	{
		while(!stk.empty()&&a[stk.top()]<a[i])
		{
			ansl2[stk.top()]=i;
			stk.pop();
		}
		stk.push(i);
	}
}
signed main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
    }
    a[0]=a[n+1]=0x7f7f7f7f;
    upl1();
    upr1();
    upl2();
    upr2();
    int ans=0;
    for(int i=1;i<=n;i++)
    {
        ans+=a[i]*((i-ansl1[i])*(ansr1[i]-i)-(i-ansl2[i])*(ansr2[i]-i));
    }
    cout<<ans;
}
2024/1/12 14:56
加载中...