【计蒜客 - 2019南昌邀请赛网络赛 - I】Max answer(单调栈,RMQ)
題干:
Alice has a magic array. She suggests that the value of a interval is equal to the sum of the values in the interval, multiplied by the smallest value in the interval.
Now she is planning to find the max value of the intervals in her array. Can you help her?
Input
First line contains an integer?n(1 \le n \le 5 \times 10 ^5n(1≤n≤5×105).
Second line contains?nn?integers represent the array?a (-10^5 \le a_i \le 10^5)a(?105≤ai?≤105).
Output
One line contains an integer represent the answer of the array.
樣例輸入復制
5 1 2 3 4 5樣例輸出復制
36題目大意:
? ?給你n個數,每個數范圍 -1e5~1e5,讓你選定一個區間,val=區間和*區間最小值,現在讓你輸出最大的val。
解題報告:
? 如果都是正數那就可以直接枚舉最小值+單調棧。時間復雜度O(n).
? 但是這題有負數,所以不能用這種貪心的方法。考慮以正數當最小值,并不影響第一種做法的正確性。考慮負數當最小值,此時可能會出現多選了一些正數的情況,但是我們深知,我們現在想要的是區間和最小,所以我們找區間最小值就可以了。但是這個最小值不能是必須以某一個數開始。考慮先求出前綴和,然后對前綴和求RMQ問題,最終得到最小值。
AC代碼:
#include<iostream> #include<cstdio> #include<algorithm> #include<cmath> #include<stack> using namespace std; typedef long long ll; const int MAX = 5e5 + 5; int n, l,r; ll maxx=-1e18; int a[MAX], L[MAX], R[MAX],qq[MAX]; ll sum[MAX],suf[MAX],dp1[MAX][25],dp2[MAX][25]; stack<int > sk; void ST() {for(int i = 1; i<=n; i++) {dp1[i][0] = sum[i];dp2[i][0] = suf[i];}for(int j = 1; (1<<j) <= n; j++) {for(int i = 1; i+(1<<j)-1 <= n; i++) {dp1[i][j] = min(dp1[i][j-1] , dp1[i + (1<<(j-1))][j-1]);dp2[i][j] = min(dp2[i][j-1] , dp2[i + (1<<(j-1))][j-1]);}}for(int i = 1; i<=n; i++) {int k = 0;while(1<<(k+1) <= i) k++;qq[i] = k;} } ll cala(int l,int r) {if(l>r) return sum[l-1];int k = qq[r-l+1];return min(dp1[l][k],dp1[r- (1<<k) + 1][k]); } ll calb(int l,int r) {if(l>r) return suf[r+1];int k = qq[r-l+1];return min(dp2[l][k],dp2[r- (1<<k) + 1][k]); } int main() {int t,i,j,k;ll tl,tr;cin>>n;for(i = 1; i<=n; i++) {scanf("%d",&a[i]);sum[i] = sum[i-1] + a[i];}for(i=n;i>=1;i--)suf[i]=suf[i+1]+a[i];for(int i = 1; i<=n; i++) {while(!sk.empty() && a[sk.top()] >= a[i]) sk.pop();if(sk.empty() ) L[i] = 0;else L[i] = sk.top();sk.push(i);}while(!sk.empty() ) sk.pop();for(int i = n; i>=1; i--) {while(!sk.empty() && a[sk.top() ] >= a[i]) sk.pop();if(sk.empty() ) R[i] = n+1;else R[i] = sk.top();sk.push(i);}ST();for(i=1;i<=n;i++){if(a[i]>=0)maxx=max(maxx,a[i]*(sum[R[i]-1]-sum[L[i]]));else {tl=cala(i+1,R[i]-1)-sum[i];tr=calb(L[i]+1,i-1)-suf[i];if(tl>0) tl=0;if(tr>0) tr=0;maxx=max(maxx,a[i]*(tl+tr+a[i]));}}printf("%lld\n",maxx);return 0 ; }?
總結
以上是生活随笔為你收集整理的【计蒜客 - 2019南昌邀请赛网络赛 - I】Max answer(单调栈,RMQ)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 世界上最大风力发电机准备首装:叶轮直径达
- 下一篇: 【POJ - 1724 】ROADS (