Thank you for participating in Kick Start 2022 Round G!
Cast
Walktober: Written by Bartosz Kostka and prepared by Nikolai Artemiev.
Curling: Written by Bintao Sun and prepared by Chun-nien Chan.
Happy Subarrays: Written by Darshan Bari and prepared by Jared Gillespie.
Cute Little Butterfly: Written by Pawan Raj and prepared by Chun-nien Chan.
Solutions, other problem preparation, reviews and contest monitoring by Abhilash Tayade, Adilet Zhaxybay, Advitiya Brijesh, Alan Lou, Anveshi Shukla, Bartosz Kostka, Bintao Sun, Bohdan Pryshchenko, Chu-ling Ko, Chun-nien Chan, Cristhian Bonilha, Darshan Bari, Ekanshi Agrawal, Eunice Hameyie, Indrajit Sinha, Jared Gillespie, Jimmy Dang, Jin Gyu Lee, Kai Hsien Boo, Kashish Bansal, Krists Boitmanis, Kunal Verma, Lizzie Sapiro Santor, Lucas Maciel, Luis Santiago Re, Manish Kundu, Mohamed Yosri Ahmed, Nikolai Artemiev, Nitish Rai, Pawan Raj, Prince Kumar, Priyam Khandelwal, Rahul Goswami, Raymond Kang, Rohan Garg, Ruiqing Xiang, Rythum, Sanyam Garg, Satish Karri, Shantam Agarwal, Swapnil Gupta, Tarun Khullar, Teja Vardhan Reddy Dasannagari, Vakul Gupta, Vinay Khilwani, Vishal Som, Yash Ranka, and Zongxin Wu.
Analysis authors:
John participates in an annual walking competition called Walktober. The competition runs for a total of $$$\mathbf{N}$$$ days and tracks the daily steps of the participants for all the $$$\mathbf{N}$$$ days. Each participant will be assigned a unique ID ranging from $$$1$$$ to $$$\mathbf{M}$$$ where $$$\mathbf{M}$$$ is the total number of registered participants. A global scoreboard is maintained tracking the daily steps of each participant.
John is determined to win Walktober this year and his goal is to score the maximum daily steps on each of the $$$\mathbf{N}$$$ days among all the participants. Having participated in Walktober last year as well, he wanted to know how many steps he fell short of in achieving his goal. Given the previous year scoreboard, calculate the minimum additional steps he needed over his last year score in order to achieve his goal of scoring the maximum daily steps every day.
The first line of the input gives the number of test cases, $$$\mathbf{T}$$$. $$$\mathbf{T}$$$ test
cases follow.
The first line of each test case contains three integers $$$\mathbf{M}$$$, $$$\mathbf{N}$$$, and $$$\mathbf{P}$$$
denoting the total number of participants, the total number of days the
competition runs, and the last year participant ID of John.
The next $$$\mathbf{M}$$$ lines describe the scoreboard of the previous year and contains
$$$\mathbf{N}$$$ integers each. The $$$j$$$-th integer of the $$$i$$$-th line
denotes the step count $$$\mathbf{S_{i,j}}$$$ of the participant with ID $$$i$$$ on the
$$$j$$$-th day of the competition.
For each test case, output one line containing
Case #$$$x$$$: $$$y$$$
, where $$$x$$$ is the test case number
(starting from 1) and $$$y$$$ is the minimum total additional steps needed by
John to achieve his goal.
Memory limit: 1 GB.
$$$1 \le \mathbf{T} \le 100$$$.
$$$1 \le \mathbf{N} \le 31$$$.
$$$1 \le \mathbf{S_{i,j}} \le 60000$$$ for all $$$i$$$ and $$$j$$$.
$$$1 \le \mathbf{P} \le \mathbf{M}$$$.
Time limit: 20 seconds.
$$$\mathbf{M} = 2$$$.
Time limit: 40 seconds.
$$$2 \le \mathbf{M} \le 1000$$$.
1 2 3 1 1000 2000 3000 1500 1500 3000
Case #1: 500
In the Sample Case, the competition ran for $$$3$$$ days and the participant ID of John was $$$1$$$. On day $$$1$$$, as the other participant has more steps, John needs $$$500$$$ additional steps. On the rest of the days, as John already has the maximum steps, he needs no additional steps. So, he needs a total of $$$500$$$ additional steps to achieve his goal.
2 3 2 3 1000 2000 1500 4000 500 4000 3 3 2 1000 2000 1000 1500 2000 1000 500 4000 1500
Case #1: 1000 Case #2: 2500
In the Sample Case #1, the competition ran for $$$2$$$ days and the participant ID of John was $$$3$$$. He needs an additional $$$1000$$$ steps on day $$$1$$$ and $$$0$$$ steps on day $$$2$$$ to achieve his goal. So, he needs a total of $$$1000$$$ additional steps to achieve his goal.
In the Sample Case #2, the competition ran for $$$3$$$ days and the participant ID of John was $$$2$$$. He needs an additional $$$0$$$ steps on day $$$1$$$, $$$2000$$$ steps on day $$$2$$$, and $$$500$$$ steps on day $$$3$$$ to achieve his goal. So, he needs a total of $$$2500$$$ additional steps to achieve his goal.
2022 is a year of the Winter Olympics! Curling has been one of the most popular winter sports as it requires skill, strategy, and sometimes a bit of luck.
In a curling game, two teams compete by sliding heavy granite stones on a long ice sheet. We call the teams the red team and the yellow team, as their stones are usually distinguished by the red and the yellow handle color. A curling game consists of several ends (subgames); in every end, the teams, each owning $$$8$$$ stones, take turns to slide them across the long ice sheet toward a circular target area called the house. A stone may hit existing stones to change its own moving direction and other stones' position (including knocking them out of play). Roughly speaking, the goal for a team is to make their stones as close to the center of the house as possible.
Geometrically, a house and a stone can be modeled as a circle and a disk (the region bounded by a circle), respectively, and the scoring rules at the conclusion of each end are formally summarized as follows.
Two teams are playing and have just delivered all their stones. The red team has $$$\mathbf{N}$$$ stones remaining on the curling sheet, centered at $$$(\mathbf{X_1}, \mathbf{Y_1}), (\mathbf{X_2}, \mathbf{Y_2}), \dots, (\mathbf{X_N}, \mathbf{Y_N})$$$, while the yellow team has $$$\mathbf{M}$$$ stones remaining, centered at $$$(\mathbf{Z_1}, \mathbf{W_1}), (\mathbf{Z_2}, \mathbf{W_2}), \dots, (\mathbf{Z_M}, \mathbf{W_M})$$$. Now you are asked to figure out the scores of both teams.
The first line of the input gives the number of test cases, $$$\mathbf{T}$$$. $$$\mathbf{T}$$$ test cases follow.
Each test case begins with a line containing the two space-separated integers $$$\mathbf{R_s}$$$ and $$$\mathbf{R_h}$$$.
The next line contains the integer $$$\mathbf{N}$$$. Then $$$\mathbf{N}$$$ lines follow, the $$$i$$$-th line of which containing the two space-separated integers $$$\mathbf{X_i}$$$ and $$$\mathbf{Y_i}$$$.
After that, similarly, the next line contains the integer $$$\mathbf{M}$$$. In the next $$$\mathbf{M}$$$ lines, the $$$i$$$-th line contains the two space-separated integers $$$\mathbf{Z_i}$$$ and $$$\mathbf{W_i}$$$.
For each test case, output one line containing
Case #$$$x$$$: $$$y$$$ $$$z$$$
, where $$$x$$$ is the test case
number (starting from 1), $$$y$$$ is the score of the red team, and $$$z$$$ is
the score of the yellow team.
Time limit: 20 seconds.
Memory limit: 1 GB.
$$$1 \le \mathbf{T} \le 100$$$.
$$$1 \le \mathbf{R_s} \lt \mathbf{R_h} \le 10^4$$$.
$$$0 \le \mathbf{N} \le 8$$$.
$$$-2 \times 10^4 \le \mathbf{X_i} \le 2 \times 10^4$$$, for
all $$$i$$$.
$$$-2 \times 10^4 \le \mathbf{Y_i} \le 2 \times 10^4$$$, for
all $$$i$$$.
$$$-2 \times 10^4 \le \mathbf{Z_i} \le 2 \times 10^4$$$, for
all $$$i$$$.
$$$-2 \times 10^4 \le \mathbf{W_i} \le 2 \times 10^4$$$, for
all $$$i$$$.
The distances between the center of each stone and the center of the house
$$$(0, 0)$$$ are distinct, i.e., no two stones are equally close to the center
of the house.
No two stones overlap (but two stones can be tangent).
$$$\mathbf{M} = 0$$$.
$$$0 \le \mathbf{M} \le 8$$$.
2 1 5 4 1 -1 6 1 0 6 -5 0 0 10 100 2 -3 -4 200 200 0
Case #1: 3 0 Case #2: 1 0
The following picture illustrates Sample Case #1. The big circle with a light blue interior represents the house, and the red disks represent the red team's stones.
In this case, the yellow team has no stones left in the house, so the red team receives a point for each of their stone in the house. All the existing stones are in the house except the one centered at $$$(6, 1)$$$ (it would have touched the house boundary if it were centered at $$$(6, 0)$$$), so the red team gets $$$3$$$ points.
2 1 5 2 1 0 -3 0 1 0 2 10 50 2 -40 -31 -35 70 3 59 0 -10 0 30 40
Case #1: 1 0 Case #2: 0 2
The following picture illustrates Sample Case #1. Besides the big circle and the red disks, the yellow disk represents the yellow team's only remaining stone.
In this case, both teams have stones inside the house. The red stone at $$$(1, 0)$$$ is in the house and no yellow stone is closer than it to the center of the house, so it is worthy of a point. Although the other red stone (centered at $$$(-3, 0)$$$) is also in the house, it is not worthy of a point because the yellow stone centered at $$$(0, 2)$$$ is closer than it to the center $$$(0,0)$$$. The yellow stone is not worthy of a point, either, due to the existence of the red stone at $$$(1, 0)$$$. Therefore, the red team gets $$$1$$$ point and the yellow team gets $$$0$$$ points.
Let us define $$$F(B, L, R)$$$ as the sum of a subarray of an array $$$B$$$ bounded by indices $$$L$$$ and $$$R$$$ (both inclusive). Formally, $$$F(B, L, R) = B_L + B_{L+1} + \cdots + B_R$$$.
An array $$$C$$$ of length $$$K$$$ is called a happy array if all the prefix sums of $$$C$$$ are non-negative. Formally, the terms $$$F(C, 1, 1), F(C, 1, 2), \dots, F(C, 1, K)$$$ are all non-negative.
Given an array $$$\mathbf{A}$$$ of $$$\mathbf{N}$$$ integers, find the result of adding the sums of all the happy subarrays in the array $$$\mathbf{A}$$$.
The first line of the input gives the number of test cases, $$$\mathbf{T}$$$. $$$\mathbf{T}$$$ test
cases follow.
Each test case begins with one line consisting an integer $$$\mathbf{N}$$$ denoting the
number of integers in the input array $$$\mathbf{A}$$$. Then the next line contains $$$\mathbf{N}$$$
integers $$$\mathbf{A_1}, \mathbf{A_2}, \dots, \mathbf{A_N}$$$ representing the integers in
given input array $$$\mathbf{A}$$$.
For each test case, output one line containing
Case #$$$x$$$: $$$y$$$
, where $$$x$$$ is the test case number
(starting from 1) and $$$y$$$ is the result of adding the sums of all happy
subarrays in the given input array $$$\mathbf{A}$$$.
Time limit: 25 seconds.
Memory limit: 1 GB.
$$$1 \le \mathbf{T} \le 100$$$.
$$$-800 \le \mathbf{A_i} \le 800$$$, for all $$$i$$$.
$$$1 \le \mathbf{N} \le 200$$$.
For at most 30 cases:
$$$1 \le \mathbf{N} \le 4 \times 10^5$$$.
For the remaining cases:
$$$1 \le \mathbf{N} \le 200$$$.
2 5 1 -2 3 -2 4 3 1 0 3
Case #1: 14 Case #2: 12
In Sample Case #1, the happy subarrays are $$$[1], [3], [3, -2], [3, -2, 4],$$$ and $$$[4]$$$ with their respective sums $$$1, 3, 1, 5,$$$ and $$$4$$$. After adding the sums obtained, the result is $$$14$$$.
In Sample Case #2, the happy subarrays are $$$[1], [1, 0], [1, 0, 3], [0], [0, 3],$$$ and $$$[3]$$$ with their respective sums $$$1, 1, 4, 0, 3,$$$ and $$$3$$$. After adding the sums obtained, the result is $$$12$$$.
In a forest of the magical world, there lies a garden full of magical creatures. The garden has plenty of flowers which are not just beautiful but also a source of energy for butterflies.
Consider the garden a 2D plane where the X-axis represents the ground, and the Y-axis represents the altitude. There are plants of infinite height on every non-negative integral point on the X-axis. There are $$$\mathbf{N}$$$ flowers in the garden, where the $$$i$$$-th flower is on the point ($$$\mathbf{X_i}$$$, $$$\mathbf{Y_i}$$$) with the nectar of some energy value $$$\mathbf{C_i}$$$.
Our cute little butterfly wants as much energy as possible to become strong. By going to the same position of a flower, the butterfly can consume its nectar and gain that flower's energy value. Each flower's nectar can only be consumed once.
The butterfly is initially at point $$$(0, 10^{18})$$$ with $$$0$$$ units of energy and facing towards the right. At any point, the butterfly can:
We know our butterfly is lazy, and it hates to move upwards during the journey. So, for this problem, we will assume that going upwards is not allowed. Also, energy can be negative at any point. Negative energy means the butterfly has spent more energy than it obtained from the flowers.
Find the maximum energy our cute butterfly can achieve.
The first line of the input gives the number of test cases, $$$\mathbf{T}$$$. $$$\mathbf{T}$$$ test
cases follow.
The first line of each test case contains two integers, $$$\mathbf{N}$$$ and $$$\mathbf{E}$$$: the
number of flowers and the energy required per turn, respectively.
The next $$$\mathbf{N}$$$ lines describe the flowers. The $$$i$$$-th line contains three
integers, $$$\mathbf{X_i}$$$, $$$\mathbf{Y_i}$$$ and $$$\mathbf{C_i}$$$: the position and the energy value of the
$$$i$$$-th flower, respectively.
For each test case, output one line containing
Case #$$$x$$$: $$$y$$$
, where $$$x$$$ is the test case number
(starting from 1) and $$$y$$$ is the maximum overall energy our cute butterfly
can achieve.
Memory limit: 1 GB.
$$$1 \le \mathbf{T} \le 100$$$.
$$$0 \le \mathbf{E} \le 10^9$$$.
$$$1 \le \mathbf{C_i} \le 10^9$$$, for all $$$i$$$.
All flowers are located at distinct points.
Time limit: 20 seconds.
$$$1 \le \mathbf{N} \le 6$$$.
$$$0 \le \mathbf{X_i} \le 500$$$, for all $$$i$$$.
$$$0 \le \mathbf{Y_i} \le 500$$$, for all $$$i$$$.
Time limit: 40 seconds.
$$$1 \le \mathbf{N} \le 10^3$$$.
$$$0 \le \mathbf{X_i} \le 500$$$, for all $$$i$$$.
$$$0 \le \mathbf{Y_i} \le 500$$$, for all $$$i$$$.
Time limit: 60 seconds.
$$$0 \le \mathbf{X_i} \le 10^5$$$, for all $$$i$$$.
$$$0 \le \mathbf{Y_i} \le 10^9$$$, for all $$$i$$$.
For at most 10 cases:
$$$1 \le \mathbf{N} \le 10^5$$$.
For the remaining cases:
$$$1 \le \mathbf{N} \le 10^4$$$.
2 4 10 1 1 2 1 2 2 2 1 2 2 2 2 6 5 1 1 4 1 3 1 3 4 5 4 3 2 5 2 1 3 2 10
Case #1: 6 Case #2: 17
In sample test case #1, there are $$$\mathbf{N} = 4$$$ flowers and $$$\mathbf{E} = 10$$$. To maximise the overall energy our butterfly can move in this way:
Hence, the total energy the butterfly got in this way is $$$6$$$ units.
In sample test case #2, there are $$$\mathbf{N} = 6$$$ flowers and $$$\mathbf{E} = 5$$$. To maximise the overall energy our butterfly can move in this way:
Hence, the total energy the butterfly got in this way is $$$17$$$ units.
We are given the daily steps count of only two people -- John, and another participant. To make sure that John had the maximum steps on each day, we just need to compare his steps on each day with the other participant's steps on that day. Let us maintain a count $$$C$$$ of the steps John needs in order to achieve his goal. Before day $$$1$$$, $$$C$$$ is equal to $$$0$$$. Then, for each day from the beginning of Walktober:
If John's steps were less than those of the other participant, we add the difference between their steps to $$$C$$$ as that is the number of additional steps John needed.
If John's steps were greater than or equal to those of the other participant, we continue to the next day as John already had the maximum steps for that day.
After the above process, we end up with the total number of steps John required last year in variable $$$C$$$.
Time and Space Complexity: Iterating over all the days would take $$$O(\mathbf{N})$$$ time. Overall time taken would be of the order of $$$O(\mathbf{N})$$$, with $$$O(1)$$$ extra space.
To help visualize the input, let us make a 2D grid of each person's steps count:
ID |
Day $$$1$$$ |
Day $$$2$$$ |
$$$\cdots$$$ |
Day $$$\mathbf{N}$$$ |
---|---|---|---|---|
$$$1$$$ | $$$\mathbf{S_{1,1}}$$$ | $$$\mathbf{S_{1,2}}$$$ | $$$\cdots$$$ | $$$\mathbf{S_{1,N}}$$$ |
$$$2$$$ | $$$\mathbf{S_{2,1}}$$$ | $$$\mathbf{S_{2,2}}$$$ | $$$\cdots$$$ | $$$\mathbf{S_{2,N}}$$$ |
$$$\cdots$$$ | $$$\cdots$$$ | $$$\cdots$$$ | $$$\cdots$$$ | $$$\cdots$$$ |
$$$\mathbf{M}$$$ | $$$\mathbf{S_{M,1}}$$$ | $$$\mathbf{S_{M,2}}$$$ | $$$\cdots$$$ | $$$\mathbf{S_{M,N}}$$$ |
To calculate the answer, we first need to calculate the maximum steps taken by
a participant each day. This would simply be the maximum step count over all
$$$\mathbf{M}$$$ participants in that day's column in the table above.
Let us denote this value for day $$$j$$$ with $$$maxOfDay(j)$$$, where $$$1
\le j \le \mathbf{N}$$$. $$$maxOfDay(j)$$$ can be calculated by traversing the day
column $$$j$$$ and keeping a track of the maximum steps encountered so far.
Again, we maintain a count $$$C$$$ of the number of steps John would have
needed to achieve his goal, starting with $$$C = 0$$$. Recall from the
statement that $$$\mathbf{P}$$$ denotes John's ID. For day $$$j$$$, John would require
$$$C_j$$$ additional steps, where:
The total number of steps John required to achieve his goal (and therefore, the answer) would then be:
Time and Space Complexity: $$$maxOfDay()$$$ runs in $$$O(\mathbf{M})$$$ time to find the maximum steps over $$$\mathbf{M}$$$ participants on a particular day. Calculating $$$maxOfDay(j)$$$ for each $$$j$$$ such that $$$1 \le j \le \mathbf{N}$$$ would take $$$O(\mathbf{M}\cdot\mathbf{N})$$$ time. Overall time taken would be of the order of $$$O(\mathbf{M}\cdot\mathbf{N})$$$, with $$$O(\mathbf{N})$$$ extra space to calculate and store $$$C_1, C_2, \dots, C_{\mathbf{N}}$$$.
Let us denote the score of the red team and the yellow team as $$$s_{red}$$$ and $$$s_{yellow}$$$, respectively.
Here is a sample code in C++:
int s_red = 0, s_yellow = 0;
for(int i = 1; i <= N; i++) {
s_red += (x[i] * x[i] + y[i] * y[i]) <= (rh + rs) * (rh + rs);
}
Here is a sample code in C++:
int dist(int x, int y) { return x * x + y * y; }
void solve() {
int s_red = 0;
for(int i = 1; i <= N; i++) {
bool is_scoring = dist(x[i], y[i]) <= (rs + rh) * (rs + rh); // Inside house.
for(int j = 1; j <= M; j++) {
is_scoring &= dist(x[i], y[i]) < dist(z[j], w[j]);
}
s_red += is_scoring;
}
int s_yellow = 0;
for(int i = 1; i <= M; i++) {
bool is_scoring = dist(z[i], w[i]) <= (rs + rh) * (rs + rh); // Inside house.
for(int j = 1; j <= N; j++) {
is_scoring &= dist(z[i], w[i]) < dist(x[j], y[j]);
}
s_yellow += is_scoring;
}
}
The overall time complexity of the above solution would be $$$O(\mathbf{N} \times \mathbf{M})$$$.
Note that the score of at least one team must be $$$0$$$. If a team does not have any stones on the curling sheet, their score is $$$0$$$. If both teams have at least one stone still in play, the opponent of the team that has the stone closest to the center will have a $$$0$$$ score.
The score of teams:
The overall time complexity of the above solution would be $$$O(\mathbf{N} + \mathbf{M})$$$.
For simplicity, let us denote subarray of array $$$\mathbf{A}$$$ starting from index $$$i$$$ and ending at index $$$j$$$, $$$(j \ge i)$$$ as $$$A(i, j)$$$.
$$$A(i, j)$$$ is a happy subarray iff all of its prefix sums are non-negative, i.e. \begin{align*} \mathbf{A_{i}} &\ge 0 \\ \mathbf{A_{i}} + \mathbf{A_{i + 1}} &\ge 0 \\ \mathbf{A_{i}} + \mathbf{A_{i + 1}} + \mathbf{A_{i + 2}} &\ge 0 \\ &\vdots\\ \mathbf{A_{i}} + \mathbf{A_{i + 1}} + \mathbf{A_{i + 2}} + \cdots + \mathbf{A_{j}} &\ge 0 \end{align*} We can observe that:
We can iterate over all subarrays with a left index $$$i$$$. For a fixed left index $$$i$$$, we can iterate over the right index $$$j$$$ such that the subarray sum is non-negative. As soon as we find an index $$$j$$$ such that subarray sum of $$$A(i, j)$$$ is less than $$$0$$$, we can stop and increase the left index.
Here is a sample code in C++.
int ans = 0;
for(int i = 1; i <= N; i++) {
int cur_sum = 0;
for(int j = i; j <= N; j++) {
cur_sum += A[j];
if(cur_sum < 0)
break;
ans += cur_sum;
}
}
The overall time complexity of the above solution would be
$$$O(\mathbf{N}^2)$$$, which is fast enough for test set $$$1$$$.
Let us denote subarray sum of $$$A(i, j)$$$ as $$$S(i, j)$$$ and prefix sum of array $$$\mathbf{A}$$$ till $$$i^{th}$$$ index as $$$P(i)$$$, \begin{align*} S(i, j) &= \mathbf{A_{i}} + \mathbf{A_{i + 1}} + \mathbf{A_{i + 2}} + \cdots +\mathbf{A_{j}} \\ P(i) &= \mathbf{A_{1}} + \mathbf{A_{2}} + \mathbf{A_{3}} + \cdots + \mathbf{A_{i}} \end{align*} The prefix sum array $$$P$$$ of array $$$\mathbf{A}$$$ can be computed in $$$O(\mathbf{N})$$$ by iterating over the array from left to right: \begin{align*} P(i) = \begin{cases} 0 & i = 0\\ P(i -1) + \mathbf{A_i} & i > 0 \end{cases} \end{align*}
By the definition of a prefix array, we can easily note that $$$S(i, j) = P(j) - P(i - 1)$$$For every index $$$i$$$, let us compute $$$nsv(i)$$$ (nearest smaller value), the smallest index $$$j$$$ such that $$$j \ge i$$$ and subarray sum of $$$A(i, j)$$$ is less than 0. If there is no such index we can simply set $$$nsv(i) = \mathbf{N} + 1$$$. Finding smallest index $$$j$$$ on right of $$$i$$$, such that the subarray sum $$$A(i, j)$$$ is less than $$$0$$$
\begin{align*} \mathbf{A_{i}} + \mathbf{A_{i + 1}} + \mathbf{A_{i + 2}} + \cdots + \mathbf{A_{j}} &\lt 0 \\ S(i, j) &\lt 0 \\ P(j) - P(i - 1) &\lt 0 \\ P(j) &\lt P(i - 1) \\ \end{align*} is same as finding the smallest index $$$j$$$, $$$j \ge i$$$ and $$$P(j) \lt P(i - 1)$$$. This can be done using small modification in All nearest smaller values algorithm in $$$O(\mathbf{N})$$$.All subarrays which starts at index $$$l$$$ and end at index $$$j$$$, such that $$$l \le j \lt nsv(l)$$$ would have non-negative sum. Sum of all such subarrays starting at index $$$l$$$ and extending at max to index $$$r$$$, $$$ r = nsv(l) - 1$$$ is same as the sum of below expressions:
\begin{align*} \mathbf{A_{l}} &= P(l) - P(l - 1) \\ \mathbf{A_{l}} + \mathbf{A_{l + 1}} &= P(l + 1) - P(l - 1) \\ \mathbf{A_{l}} + \mathbf{A_{l + 1}} + \mathbf{A_{l + 2}} &= P(l + 2) - P(l - 1) \\ &\vdots\\ \mathbf{A_{l}} + \mathbf{A_{l + 1}} + \mathbf{A_{l + 2}} + \cdots + \mathbf{A_{r}} &= P(r) - P(l -1) \end{align*} On simplification, sum of all subarray $$$A(i, j)$$$ such that $$$i = l$$$ and $$$i \le j \le r$$$ \begin{align*} sum(l) = (P(l) + P(l + 1) + P(l + 2) + \cdots + P(r)) - (r - l + 1) \times P(l - 1) \end{align*} The first term $$$P(l) + P(l + 1) + P(l + 2) + \cdots + P(r)$$$ can be computed by pre-calculating the prefix sum array of $$$P$$$.Let us denote prefix sum of $$$P$$$ as $$$PP$$$, i.e. $$$ PP(i) = P(1) + P(2) + \cdots + P(i)$$$. The above sum can be simplified as:
\begin{align*} sum(l) &= PP(r) - PP(l - 1) - (r - l + 1) \times P(l - 1) \\ ans &= \sum\limits_{l=1}^{N} sum(l) \\ ans &= \sum\limits_{l=1}^{N} PP(r) - PP(l - 1) - (r - l + 1) \times P(l - 1) \end{align*}Nearest smaller value on right for each index in prefix array $$$nsv(i)$$$ can be computed in $$$O(\mathbf{N})$$$. Sum of all subarrays with fixed left index and moving right index can be computed in $$$O(1)$$$, if we have pre computed prefix sum array of $$$\mathbf{A}$$$ i.e. $$$P$$$ and prefix sum array of $$$P$$$ i.e. $$$PP$$$. Precomputation of prefix sum arrays can be done in $$$O(\mathbf{N})$$$. The overall time complexity of the above solution would be $$$O(\mathbf{N})$$$
Let us introduce some notation first.
For $$$\mathbf{N} \le 6$$$, we can enumerate all valid sequences of flowers and take the sequence yielding the highest energy. A sequence of flowers is valid if their $$$y$$$-coordinates form a non-increasing sequence and thus do not require any upward moves, which are illegal. As we visit the flowers one by one, there is no incentive of changing the direction if the next flower can be reached without doing so. This leads to the following recursive method using Python-like syntax:
used = [False] * N ans = 0 enumerate(x=0, y=Y_max+1, is_right=True, energy=0) print(ans) def enumerate(x, y, is_right, energy): ans = max(ans, energy) for i in range(N): if not used[i] and Y[i] <= y: used[i] = True if (is_right and X[i] < x) or (not is_right and X[i] > x): # Need to change direction to reach the i-th flower enumerate(X[i], Y[i], not is_right, energy + C[i] - E) else: # Can reach the i-th flower without changing the direction enumerate(X[i], Y[i], is_right, energy + C[i]) used[i] = False
The time complexity of this brute-force method is $$$O(\mathbf{N}!)$$$.
Let us define another function.
The following observation will simplify our reasoning about the problem. Since going straight without changing the direction does not consume any energy, we can assume that direction changes happen at the $$$x$$$-coordinates $$$0$$$ and $$$X_\max$$$ only. This, in turn, implies the existence of an optimal path where the flowers at the same $$$y$$$-coordinate are visited in one straight movement from left to right or from right to left without changing the direction in between. Therefore, we can clearly distinguish between the two scenarios when the flowers at level $$$y$$$ are visited in the right or left direction.
Let $$$r(x,y)$$$ be the maximum energy of a path ending at the point $$$(x,y)$$$ when the flowers at level $$$y$$$ are visited in the right direction, and let us define a similar function $$$l(x,y)$$$ for the left direction. The final answer is then $$$\max_{0 \leq x \leq X_\max,0 \leq y \leq Y_\max}\max(r(x,y),l(x,y))$$$.
The values of $$$r(x,y)$$$ and $$$l(x,y)$$$ can be computed using dynamic programming and the following recurrence relations. As the relations suggest, we should calculate the functions $$$r(x,y)$$$ and $$$l(x,y)$$$ for higher values of $$$y$$$ first. For points in the same $$$y$$$ level, we calculate $$$r(x,y)$$$ from left to right, and $$$l(x,y)$$$ from right to left.
The following image illustrates these recurrence relations.
The time complexity of such a dynamic programming solution is $$$O(X_\max \times Y_\max)$$$, which is efficient enough as the coordinates are bounded by $$$500$$$.
For the large test set, the coordinate space is not reasonably restricted, so we should confine the calculation of $$$r(x,y)$$$ and $$$l(x,y)$$$ to the set of points with flowers. The general dynamic programming idea remains the same, though.
Assuming that we are currently processing the flower $$$i$$$, let us consider the recurrence relation (6). We can reach the $$$i$$$-th flower from any processed flower $$$j$$$ moving in the right direction if $$$\mathbf{X_j} \leq \mathbf{X_i}$$$. Among all such flowers $$$j$$$, we are looking for the one with the largest $$$r(\mathbf{X_j}, \mathbf{Y_j})$$$. To make such a lookup efficient, let us store the processed flowers in a set $$$S_r$$$ sorted by $$$\mathbf{X_j}$$$. Moreover, if $$$\mathbf{X_j} \leq \mathbf{X_k}$$$ for two processed flowers $$$j \neq k$$$ and $$$r(\mathbf{X_j},\mathbf{Y_j}) \geq r(\mathbf{X_k},\mathbf{Y_k})$$$, we can safely ignore the flower $$$k$$$ and drop it from $$$S_r$$$, so the set is essentially increasing by values $$$r(\mathbf{X_j},\mathbf{Y_j})$$$ as well. Now, to find the best processed flower $$$j$$$ to visit the current flower $$$i$$$ from, we just look for the flower $$$j$$$ in $$$S_r$$$ with the highest $$$\mathbf{X_j}$$$ such that $$$\mathbf{X_j} \leq \mathbf{X_i}$$$. Once we are done calculating $$$r(\mathbf{X_i},\mathbf{Y_i})$$$, we add the flower $$$i$$$ to the set $$$S_r$$$ and potentially drop some other flowers to maintain the sorted property of the set.
In order to facilitate the calculation of $$$l(x,y)$$$, we should maintain a similar set of processed flowers $$$S_l$$$, which is increasing by the coordinates $$$\mathbf{X_j}$$$ and decreasing by the values $$$l(\mathbf{X_j},\mathbf{Y_j})$$$.
Equipped with the sets $$$S_r$$$ and $$$S_l$$$, we can also handle the border cases like items (5) and (7) above. Suppose we have calculated the functions $$$r$$$ and $$$l$$$ for all flowers $$$i$$$ with $$$\mathbf{Y_i} \gt y$$$ for some level $$$y$$$ and we are about to process the flowers $$$i$$$ with $$$\mathbf{Y_i}=y$$$. Let $$$a$$$ be the first (i.e. leftmost) flower in $$$S_l$$$ and $$$b$$$ be the last (i.e. rightmost) flower in $$$S_r$$$. To account for the change of direction before visiting the leftmost flower $$$i$$$ with $$$\mathbf{Y_i}=y$$$, we should make sure $$$r(\mathbf{X_i}, \mathbf{Y_i})$$$ is at least $$$l(\mathbf{X_a}, \mathbf{Y_a}) + \mathbf{C_i} - \mathbf{E}$$$ in analogy with the recurrence relation (5) above. Similarly, for the rightmost flower $$$i$$$ with $$$\mathbf{Y_i}=y$$$, $$$l(\mathbf{X_i}, \mathbf{Y_i})$$$ is at least $$$r(\mathbf{X_b}, \mathbf{Y_b}) + \mathbf{C_i} - \mathbf{E}$$$ in analogy with the recurrence relation (7).
The time complexity of this modified dynamic programming approach is $$$O(\mathbf{N} \log \mathbf{N})$$$, as it involves sorting the flowers by their coordinates and using a standard sorted set data structure with $$$O(\log \mathbf{N})$$$ time per operation.