題目意思: \(\displaystyle \sum^j_{y=i}X_y, (1 \leq i\leq j \leq N)* min(X_{i}|1 \leq i \leq N)\)優化
PS:這題要多組讀入,C++ cout cin記得優化spa
#include <iostream> #include <stack> using namespace std; typedef long long int ll; const int MAXN = 1e6 + 7; ll height[MAXN],sum[MAXN]; int Left,Right; int n; ll solve(){ ll ans = 0; stack<int> s; height[n+1] = -1; Left = Right = 1; for(int i=1;i<=n+1;i++){ while(!s.empty() && height[s.top()] > height[i]){ int cur = s.top(); s.pop(); int _left = (s.empty()?1:s.top()+1); int _right = i-1; ll tmp = height[cur]*(sum[_right]-sum[_left-1]); if(tmp > ans){ ans = tmp; Left = _left; Right = _right; } } s.push(i); } return ans; } int main(){ while(~scanf("%d",&n)){ sum[0] = 0; for(int i=1;i<=n;i++) { scanf("%lld",&height[i]); sum[i] = sum[i-1] + height[i]; } printf("%lld\n",solve()); printf("%d %d\n",Left,Right); } return 0; }