Link to the question: Inter-zone C _
Idea: Calculate contribution and find the number of intervals where each number is the current maximum and the number of intervals where each number is the minimum.
Similar to this question, it has a better edible effect. Click here.
# Include <bits/stdc ++. h> using namespace STD; # define maxn 100005 # define ll long longll ll [maxn], RR [maxn], a [maxn]; ll work (ll n) {memset (LL, 0, sizeof (LL); memset (RR, 0, sizeof (RR); stack <int> S, T; For (LL j = 1; j <= N; j ++) {While (S. size () & A [J]> = A [S. top ()]) {S. pop () ;}if (! S. size () ll [J] = 1; else ll [J] = S. top () + 1; S. push (j) ;}for (ll j = N; j> = 1; j --) {While (T. size () & A [J]> A [T. top ()]) {T. pop () ;}if (! T. size () rr [J] = N; else RR [J] = T. top ()-1; T. push (j);} ll ans = 0; For (LL j = 1; j <= N; j ++) {ans + = 1ll * A [J] * 1ll * (RR [J]-ll [J] + (RR [J]-j) * (J-ll [J]);} return ans;} int main () {ll t; CIN> T; while (t --) {ll N; cin> N; For (LL j = 1; j <= N; j ++) {scanf ("% d", & A [J]);} ll ans = work (n); // cout <ans <Endl; For (LL j = 1; j <= N; j ++) {// when the value is assigned, the result equivalent to finding the maximum value is a negative number, which is equal to minus a [J] =-A [J];} ans + = work (N ); cout <ans <Endl ;}}
Nowcoder -- Niuke lefa red packet off single ACM competition C _ zone Interval