leetcode2281 巫师的总力量和
作者:互联网
思路:
单调栈计算出每个数字的“管辖范围”,再对每个“管辖范围”单独计算并求和。
实现:
1 class Solution { 2 public: 3 int totalStrength(vector<int>& a) { 4 int n=a.size(); 5 vector<int>left,right; 6 stack<int>st; 7 st.push(-1); 8 for(int i=0;i<n;i++){ 9 while(st.top()>=0 and a[i]<=a[st.top()]){ 10 st.pop(); 11 } 12 left.push_back(st.top()); 13 st.push(i); 14 } 15 while(!st.empty())st.pop(); 16 st.push(n); 17 for(int i=n-1;i>=0;i--){ 18 while(st.top()<n and a[i]<a[st.top()]){ 19 st.pop(); 20 } 21 right.push_back(st.top()); 22 st.push(i); 23 } 24 reverse(right.begin(),right.end()); 25 int mod=1e9+7; 26 int res=0; 27 vector<long long>pre(n+1,0); 28 for(int i=0;i<n;i++){ 29 pre[i+1]=(pre[i]+a[i])%mod; 30 } 31 vector<long long>prepre(n+2,0); 32 for(int i=1;i<=n;i++){ 33 prepre[i+1]=(prepre[i]+pre[i])%mod; 34 } 35 for(int i=0;i<n;i++){ 36 int l=left[i]+1; 37 int r=right[i]-1; 38 int tmp=(prepre[r+2]-prepre[i+1]+mod)%mod*(i-l+1)%mod; 39 int tmp2=(prepre[i+1]-prepre[l]+mod)%mod*(r-i+1)%mod; 40 res=(res+(long long)a[i]*(tmp-tmp2+mod)%mod)%mod; 41 } 42 return res; 43 } 44 };
标签:pre,right,totalStrength,leetcode2281,巫师,st,int,管辖,力量 来源: https://www.cnblogs.com/wangyiming/p/16320937.html