817D - Imbalanced Array - CodeForces Solution


data structures divide and conquer dsu sortings *1900

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>
#define ll long long
#define INF 0x3f3f3f3f
#define N 1000007
using namespace std;
int n, a[N], l[N], r[N];
ll ans;
inline int read(){
    int ans = 0, f = 1;
	char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar())
		if (ch == '-')
		    f = 0;
	for(; ch >= '0' && ch <= '9'; ch = getchar())
	    ans = (ans << 3) + (ans << 1) + ch - 48;
	return f? ans: -ans;
}
int main(){
    n = read();
    ans = 0;
    for (int i = 1;i <= n; ++i)
	    a[i] = read();
    for (int i = 1; i <= n; ++i)
	    l[i] = r[i] = i;
    for (int i = 2; i <= n; ++i){
        int now = i;
        while (now > 1 && a[i] >= a[now - 1])
		    now = l[now - 1];
        l[i] = now;
    }
    for (int i = n - 1; i >= 1; --i){
        int now = i;
        while (now < n && a[i] > a[now + 1])
		    now = r[now + 1];
        r[i] = now;
    }
    for (int i = 1;i <= n; ++i)
	    ans += (ll)a[i] * (ll)(i - l[i] + 1) * (ll)(r[i] - i + 1);
    for (int i = 2; i <= n; ++i){
        int now = i;
        while (now > 1 && a[i] <= a[now - 1])
		    now = l[now - 1];
        l[i] = now;
    }
    for (int i = n - 1; i >= 1; --i){
        int now = i;
        while (now < n && a[i] < a[now + 1])
		    now = r[now + 1];
        r[i] = now;
    }
    for (int i = 1;i <= n; ++i)
	    ans -= (ll)a[i] * (ll)(i - l[i] + 1) * (ll)(r[i] - i + 1);
    printf("%lld\n", ans);
}
	    	   	 	  	 		 	  	 		  			


Comments

Submit
0 Comments
More Questions

1546B - AquaMoon and Stolen String
1353C - Board Moves
902A - Visiting a Friend
299B - Ksusha the Squirrel
1647D - Madoka and the Best School in Russia
1208A - XORinacci
1539B - Love Song
22B - Bargaining Table
1490B - Balanced Remainders
264A - Escape from Stones
1506A - Strange Table
456A - Laptops
855B - Marvolo Gaunt's Ring
1454A - Special Permutation
1359A - Berland Poker
459A - Pashmak and Garden
1327B - Princesses and Princes
1450F - The Struggling Contestant
1399B - Gifts Fixing
1138A - Sushi for Two
982C - Cut 'em all
931A - Friends Meeting
1594A - Consecutive Sum Riddle
1466A - Bovine Dilemma
454A - Little Pony and Crystal Mine
2A - Winner
1622B - Berland Music
1139B - Chocolates
1371A - Magical Sticks
1253A - Single Push