日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【计蒜客 - 2019南昌邀请赛网络赛 - I】Max answer(单调栈,RMQ)

發布時間:2023/12/10 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【计蒜客 - 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)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。