题目描述
One day, Snuke was given a permutation of length N, a1,a2,…,aN, from his friend.
Find the following:
Constraints
1≤N≤200,000
(a1,a2,…,aN) is a permutation of (1,2,…,N).
Find the following:
Constraints
1≤N≤200,000
(a1,a2,…,aN) is a permutation of (1,2,…,N).
输入
The input is given from Standard Input in the following format:
N
a1 a2 … aN
N
a1 a2 … aN
输出
Print the answer.
Note that the answer may not fit into a 32-bit integer.
Note that the answer may not fit into a 32-bit integer.
样例输入
3
2 1 3
样例输出
9
这是一道单调栈
单调栈的总结:https://blog.csdn.net/wubaizhe/article/details/70136174
#include <bits/stdc++.h> using namespace std; typedef long long ll; const int maxn = 2e5+10; struct node { ll pre; ll net; ll num; }; stack<node>sp; ll s[maxn]; int main() { ios::sync_with_stdio(false); int n; cin>>n; for(int i=1;i<=n;i++) cin>>s[i]; ll ans=0; node fr,to; fr.net=fr.pre=1; fr.num=s[1]; sp.push(fr); for(int i=2;i<=n;i++){ to.num=s[i]; to.pre=to.net=1; while(!sp.empty()&&to.num<=sp.top().num){ fr=sp.top(); sp.pop(); if(!sp.empty()) sp.top().net+=fr.net; to.pre+=fr.pre; ans+=fr.pre*fr.num*fr.net; } sp.push(to); } while(!sp.empty()) { fr=sp.top(); sp.pop(); if(!sp.empty()) sp.top().net+=fr.net; ans+=fr.pre*fr.num*fr.net; } cout<<ans<<endl; return 0; }
单调栈对求前后的有多少比他大/小很高效
1.首先这个运算要简化成:前面的大值*后面的大值(紧接的并且加上本身)
2.然后就是栈,极其烧脑┭┮﹏┭┮