单调栈+dp
https://codeforces.com/contest/1313/problem/C2
题意:给出一组数,使这组数满足任意ai不存在j<i<k,a[j] > a[i] < a[k],求满足该条件的这组数和的最大值?
解法:单调递增栈,扩展出以每个数为最小值的左右区间,同时dp可以算出1-i左区间以该值为最小值的最大和,右区间同理。
#include<bits/stdc++.h> typedef long long ll ; #define int ll #define mod 1000000007 #define gcd __gcd #define rep(i , j , n) for(int i = j ; i <= n ; i++) #define red(i , n , j) for(int i = n ; i >= j ; i--) #define ME(x , y) memset(x , y , sizeof(x)) //ll lcm(ll a , ll b){return a*b/gcd(a,b);} //ll quickpow(ll a , ll b){ll ans=1;while(b){if(b&1)ans=ans*a%mod;b>>=1,a=a*a%mod;}return ans;} //int euler1(int x){int ans=x;for(int i=2;i*i<=x;i++)if(x%i==0){ans-=ans/i;while(x%i==0)x/=i;}if(x>1)ans-=ans/x;return ans;} //const int N = 1e7+9; int vis[n],prime[n],phi[N];int euler2(int n){ME(vis,true);int len=1;rep(i,2,n){if(vis[i]){prime[len++]=i,phi[i]=i-1;}for(int j=1;j<len&&prime[j]*i<=n;j++){vis[i*prime[j]]=0;if(i%prime[j]==0){phi[i*prime[j]]=phi[i]*prime[j];break;}else{phi[i*prime[j]]=phi[i]*phi[prime[j]];}}}return len} #define SC scanf #define INF 0x3f3f3f3f #define PI acos(-1) #define pii pair<int,int> #define fi first #define se second #define lson l,mid,root<<1 #define rson mid+1,r,root<<1|1 using namespace std; const int maxn = 5e5+9; const int N = 10000 ; int s[maxn] , top ; int a[maxn] , l[maxn] , r[maxn]; void solve(){ int n ; cin >> n ; rep(i , 1 , n){ cin >> a[i]; } a[n+1] = a[0] = -INF; rep(i , 1 , n+1){ while(top && a[s[top]] >= a[i]) top--; if(!top) l[i] = a[i] * i ; else l[i] = l[s[top]] + (i - s[top]) * a[i]; s[++top] = i ; } top = 0 ; red(i , n , 0){ while(top && a[s[top]] >= a[i]) top--; if(!top) r[i] = a[i] * (n-i+1) ; else r[i] = r[s[top]] + (s[top] - i) * a[i]; s[++top] = i ; } int id = -1 , ans = -INF; rep(i , 1 , n){ int temp = l[i] + r[i] - a[i]; if(temp > ans){ id = i ; ans = temp; } } red(i , id-1 , 1) a[i] = min(a[i+1] , a[i]); rep(i , id+1 , n) a[i] = min(a[i] , a[i-1]); rep(i , 1 , n) cout << a[i] << " " ; } signed main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); //int t ; //cin >> t ; //while(t--){ solve(); //} }