Nef 2023 Tutorial
Nef 2023 Tutorial
Let us break each list of integers into sublists greedily: 1) we go over elements maintaining their sum and
the minimum sum seen so far; 2) when the sum becomes positive we split the list and store the sum and
the minimum observed sum; and 3) we continue with the list from the step 1 until it becomes empty.
Then, we populate the priority queue with the first lists of each list sorted by the minimum observed
sum. Now, we should take the sublist with the biggest minimum sum — it reduces the chances to make
x non-negative while increasing it, at the end. Thus, in each step, we take the sublist with the biggest
minimum and apply it to x. Then, we withdraw this sublist from the corresponding list i and put the
next sublist from the list i into the priority queue.
Page 1 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
• If cactuses consist of only cycles of length 3 and don’t contain any bridges, then there is no
transformation from the first cactus into the second one because if we remove any edge from the
first cactus, we can not add the new one (we need to add the same deleted edge).
For all the other cases, the solution exists. To solve the problem, we will transform both cactuses into the
same convenient cactus, let’s call it as star cactus. If the cactus contains n vertices and c cycles, then the
star cactus will have the following cycles: (1, 2, 3), (1, 4, 5), . . ., (1, 2x, 2x + 1), all the cycles contain the
vertex 1. The bridges of the star cactus will be (1, 2x + 2), (1, 2x + 3), . . ., (1, n), all the bridges will be
incident to the vertex 1.
Operations for transforming the first cactus into the second one will be the concatenation of operations
for transforming the first cactus into the star cactus and operations for transforming the second cactus
into the star cactus but already in reverse order.
So, let’s understand how we can transform any cactus into a star cactus. Before understanding the actions
needed for an algorithm, let’s do some denotations:
• Let’s denote by distv — the minimum distance from the vertex 1 to the vertex v (1 ≤ v ≤ n).
First action: let’s take any cycle c1 , c2 , ..., ck of length k (where k > 3), and do the following operation
on it:
• Remove an edge (c1 , ck ) from the cactus and add an edge (c1 , c3 ).
After applying this operation, the number of cycles of length greater than 3 will be decreased by 1. We
will perform the following action while the cactus contains any cycle of length greater than 3.
̸ 1, and u ̸= 1.
Second action: let’s take any bridge (v, u) from the cactus, such that distv < distu , v =
Remove an edge (v, u) from the cactus and add an edge (1, u). We will perform this action while the
cactus contains any bridge that isn’t incident to the vertex 1.
Third action: let’s take any edge (1, v) that is incident to the vertex 1 and degv > 2. There are two cases:
Case 1: Edge (1, v) is bridge.
We can note that degv is odd because the number of bridges incident to any vertex is at most 1. Since
degv > 2, we know that there is at least one cycle that contains the vertex v. Let’s take any cycle that
contains the vertex v and assume that the vertices of the cycle are v, u, and w. Let’s do the following
operations:
Let’s note that after these operations, the number of cycles that contain the vertex 1 will be increased by
1, while the number of bridges incident to the vertex 1 will not be changed.
Case 2: Edge (1, v) isn’t bridge.
Page 2 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
We can note that degv is even because all the bridges are incident to the vertex 1. We know that an edge
(1, v) isn’t a bridge, so let’s assume the vertices of the cycle containing an edge (1, v) are 1, v and a.
Since degv > 2, we know that there are at least two cycles that contain the vertex v. So, let’s take any
cycle that contains the vertex v and is different from the cycle (1, v, a). Let’s assume that the vertices of
the cycle are v, u, and w. Let’s also understand that there is at least one bridge in the cactus because all
the cases that don’t contain a bridge were considered initially as edge cases. So, let’s take some bridge (1,
b) incident to the vertex 1. Let’s do the following operations:
Let’s note that after these operations, the number of cycles that contain the vertex 1 will be increased by
1, while the number of bridges incident to the vertex 1 will not be changed.
We will perform this action with two cases while the cactus contains any vertex v ̸= 1, such that degv > 2.
After all of these three actions, we will get the structure of the star cactus, and it remains to fix the labels
in the vertices. In the picture below, you can see the operations that are needed for swapping two labels
(in the example below, we swapped the labels 3 and 4).
1 1
6 6
2 5 2 5
3 4 3 4
1 1
6 6
2 5 2 5
4 3 4 3
In practice, the number of operations for this solution is approximately 5000, but for solid proof, you can
see that it can’t be greater than 15000.
Page 3 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
Let’s pick a positive integer X without leading or trailing zeros. Consider an expression X+X-0. Its value
is 2X, but the reversed expression evaluates to 0-rev(X)+rev(X)=0. Let’s call this expression f(X). The
result of evaluating f(X) is 2X and the result of evaluating rev(f(X)) is 0. Thus, when both p and q are
even, f( p2 )+rev(f( 2q )) is a possible answer. For negative X, define f(X) to be 0-|X|-|X|.
When p or q is odd, let’s make both of them even. First, if they have different parities, add 12+ in the
beginning. This would add 12 to the value of p and 21 to the value of q, so now they have the same parity.
If they are both odd, append +1.
The remaining issue to be solved is that p and q might have trailing zeros. This can be solved by adding
+x instead of +1 in the last step (such x that makes p and q both even, but not ending with 0, always
exists). The maximum length of such an expression is 4 + 2 · (4 + 2 · len( p2 )) ≤ 84.
The larger limit on the length of the answer allowed for many other approaches. For example, you can use
the fact that 12-4*4+5 is a solution for p = 1, q = 0, multiply it by any number, and add it with its reverse.
Another approach (yielding significantly longer expressions) is to use numbers like xx..xx (or palindromes
in general), xx..xy..yy, 9*9*...*9*x to make the input numbers (either p and q independently, or, their
difference and an offset). Depending on the specific construction, this type of solution also has a good
chance to pass the tests.
Page 4 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
reasoning, it can be shown that the fugitive only needs to chosse his shelter at the beginning of the game
and after the police officer getting into a leaf (and thus triggering the initial state).
Therefore, the decisions in this game are only made in initial states. Thus, we can condense the game to
its initial states only and assume that the game now is as follows. The police officer appears in vertex s.
Then the players take turns, starting with the fugitive. At his turn, the fugitive, who knows the current
position of the police officer, chooses a leaf f , different from the police officer’s position, and sits there.
At the police officer’s turn, she chooses a leaf p′ and walks there from her current vertex p, spending
dist (p, p′ ) minutes. Then, if p′ ̸= f , the game continues, otherwise, it ends.
In this setting it is easy to see that one move takes at most n − 1 minutes, and the police officer can guess
1
the correct leaf and finish the game with probability at least n−1 , therefore, the mathematical expectation
of the duration of the game, assuming the optimal play by the police officer, is no more than (n − 1)2 , in
particular, it is finite.
Due to Nash, there is a pair of optimal strategies called the Nash equilibrium, in which the probabilistic
distribution only depends on the position of the police officer. Therefore, we have completed the proof of
the fact in question.
Let us fix the optimal strategy. Denote by pu,v the probability that, if the police officer is initially in u,
she chooses to walk to v. Denote by qu,v the probability that, if the police officer is initially in u, the
fugitive chooses to hide in v. Denote by xu the mathematical expectation of the duration of the game if
the police officer is initially in u. According to the previous reasoning, pu,v = qu,v = 0 unless v is a leaf
different from u.
We will prove the converse: both pu,v and qu,v are positive if v is a leaf different from u. To see why,
firstly we will assume that qu,v = 0 — that is, when the police officer is in u the fugitive never choses to
hide in v. Then the police officer, if pu,v > 0, can modify her strategy so that she does not visit v, e.g. by
stopping right before visiting v and choosing the next leaf right there. This circumstance would violate
the Nash equilibrium. Therefore, qu,v = 0 implies pu,v = 0. Similarly, one can deduce that if pu,v = 0 for
a leaf v ̸= u but pu,v′ > 0 for some other leaf v ′ then qu,v′ = 0: otherwise, the fugitive could modify his
strategy and hide in v instead of v ′ , ensuring he doesn’t get caught and prolonging the chase. But, as we
showed earlier, qu,v′ = 0 implies pu,v′ = 0, and that leads to a contradiction. So pu,v cannot equal zero for
a leaf v ̸= u, and so cannot qu,v .
So, each of pu,v and qu,v is non-zero if and only if v is a leaf different from u. Our last goal is to calculate
the values of pu,v , qu,v and xu . To do that, we will write down several equations on these numbers. Denote
by L the set of leaves of the tree. Firstly, xu , as the mathematical expectation of the duration of the chase,
satisfies: ∑
xu = F (u, v) where F (u, v) = pu,v (dist (u, v) + (1 − qu,v )xv ).
v∈L\{u}
Also, as a solution to an optimization problem, pu,v and qu,v satisfy complementary slackness
conditions (as a part of Karush–Kuhn–Tucker conditions). Namely, note that if, for a fixed u,
Pu (v) = ∂p∂u,v F (u, v) = (dist (u, v) + (1 − qu,v )xv ) differs for two different vertices v ∈ L \ {u}, then
it would be profitable for the police officer to always walk into the vertex with the lower value of Pu (v),
and that would violate the Nash equilibrium. Similarly, for a fixed u, Qu (v) = ∂q∂u,v F (u, v) = −pu,v xv
should be equal among all v ∈ L \ {u}, otherwise the fugitive would have the incentive to only hide in the
vertices v with the maximum Qu (v) and violate the Nash equilibrium from his side.
The aforementioned complementary slackness conditions can be reformulated in the following way: if in
the function F (u, v) = pu,v (dist (u, v) + (1 − qu,v )xv ) one replaces the array pu,v with any other array
with a unit sum, which vanishes on v ∈ / L \ {u}, then the value of F (u, v) does not change. Similarly, if
one replaces the array qu,v with any other array with a unit sum, which vanishes on v ∈ / L \ {u}, then the
value of F (u, v) does not change. (But if one does the both modifications, then F (u, v) might change.)
Now we are ready to write a system of equations on the numbers xu . All numbers pu,v xv are equal to each
Page 5 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
therefore,
1/xv
pu,v = ∑ .
w∈L\{u} 1/xw
1/xv
F (u, v) = ∑ (dist (u, v) + (1 − qu,v )xv ).
w∈L\{u} 1/xw
It was said earlier that the array qu,v can be chosen arbitrarily if the unit sum is preserved. We will fix a
vertex t ∈ L \ {u} and take qu,v = [v = t] — that is, qu,t = 1 and the rest of the qu,v are taken zero. After
this substitution, F (u, v) stays the same:
1/xv
F (u, v) = ∑ (dist (u, v) + xv − [v = t]xt ).
w∈L\{u} 1/xw
The xv − [v = t]xv part can be removed from under the summation sign:
|L \ {u}| 1 ∑ 1/xv
xu = ∑ −∑ + ∑ dist (u, v).
w∈L\{u} 1/xw w∈L\{u} 1/xw v∈L\{u} w∈L\{u} 1/xw
However, to get a bit more symmetric form, one can multiply it by the denominator:
∑ ∑
xu · 1/xv = |L| − 2 + [u ∈/ L] + dist (u, v)/xv .
v∈L\{u} v∈L\{u}
Then, if u ∈ L, we can add one to both sides (or, equivalently, add [u ∈ L] to both sides):
∑ ∑
xu · 1/xv = |L| − 1 + dist (u, v)/xv .
v∈L v∈L
Unfortunately, this system of equations is very unlikely to have a clear way to be solved analytically in
general case. Even for small trees the exact formulae begin to look gargantuan, and there are really few
classes of trees with neat formulae (e.g. star, bamboo, pair of equal stars connected by a bamboo). Instead,
one can take some initial approximation, e.g. xu = 1 or xu = (n − 1)2 , and iteratively apply the formula
above to get a more and more precise answer. This process seems to converge relatively fast, although
jury does not have a proof of that. What is worth noting is that, at first, it is reasonable to only calculate
xu for u ∈ L (since these are the only xu which occur in the right hand side), and in the end, when the
Page 6 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
leaf expectations are already calculated with satisfying precision, calculate the rest of the expectations
with one iteration over all u ∈ L.
One more possible speedup is to work with yu = 1/xu instead of xu , since this would lead to a much
smaller number of divisions: ∑
yv
yu = ∑v∈L .
|L| − 1 + v∈L dist (u, v)yv
( ) ( )
This final approach works in O nℓ + qℓ2 + nℓ = O nℓ + qℓ2 , where n = |V |, ℓ = |L| and q is the number
of iterations: the first nℓ summand stands for finding the pairwise distances between the vertices and the
leaves, qℓ2 stands for the iterative algorithm for finding the leaf values of xu , and the last nℓ summand
stands for calculating the rest of the values of xu . In practice, for n ≤ 100, q = 1500 or q = 2000 and a
64-bit floating point number type were enough to pass all tests, depending on the quality of the initial
approximation. The time limit for this problem is pretty loose, so even Python solutions should pass with
a reasonable implementation.
Define sequences p and q such that pi = max(a0 , a1 , . . . , ai ), and qi = max(ai , ai+1 , . . . , an−1 )
∑ ∑
Observe that the amount of accumulating rain is ∑ n−1
i=0 min(pi , qi ) − ai . It’s easy to update i ai based
n−1
on the range increase operation, so let’s focus on i=0 min(pi , qi ).
A critical observation is that pi is (non-strictly) increasing function, while qi is (non-strictly) decreasing
function. Another critical observation is that operation a[l..r]+=1 only causes at most one range update
for p: p[l′ ..r′ ]+=1 (if p would change at all, the first element to increase would be the leftmost element on
segment [l; r] larger than max(a0 , . . . , al−1 ), and this increase will go until first sufficiently large element
to the right of it. Both indices can be found with standard segment tree algorithms in O(log n) time).
Similarly there at most one range update q[l′′ ..r′ ]+=1.
There are some different ways how to finalize calculation give those ideas. For instance, one can store a
segment tree for pi − qi (observe this is monotonically increasing function),∑n−1and then at each p[l..r]
+=1 and q[l..r]+=1 range operations caused by above, recompute how i=0 min(pi , qi ) is changing.
Specifically, min(pi , qi ) will increase during p[l..r]+=1 operation for indices i such that pi < qi .
Let’s build a directed graph with edges ai → bi . Consider a (weakly) connected component in this graph.
Let the size of this component be k.
For the acyclic component, we can deliver all the passengers in k−1 launches, making the chain of launches
in the topological order.
If the component is not acyclic, we need to make at least one cycle of launches, so we need k launches. It
can be shown that if it is possible to deliver all the passengers, it is possible to do it by making one big
cycle of launches. Now let’s look at the first launch, say v → u. If we remove this launch, it will affect only
passengers with ai = v. So if we remove these edges, the remaining edges must form acyclic graph. We
can iterate over all vertices v and check if removing this vertex makes the component acyclic, in O(nm)
time.
Page 7 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
Let us define the function f (φ) as the value of pressure imbalance for the polygon rotated by angle φ.
1
∫2π
As the answer to the problem we want to calculate 2π f (φ)dφ.
0
Let us define the function pi (φ) = −xi · sin (φ) + yi · cos (φ). It is a coordinate of projection of vertex i
into the orthogonal direction to the water level.
If vertices u1 , u2 , . . . , uk are underwater, when
k ( ) k ( )
1∑ k 1∑ k
f (φ) = max duj − dui = pui (φ) − min puj (φ)
k j=1 k j=1
i=1 i=1
( ) ( )
1∑ 1∑
k k
k
f (φ) = − xui sin (φ) + yui cos (φ) − min puj (φ)
k k j=1
i=1 i=1
k n
Let’s note, that min puj (φ) = min pi (φ), because the global lowest vertex will be underwater. So:
j=1 i=1
( ) ( )
1∑ 1∑
k k
n
f (φ) = − xui sin (φ) + yui cos (φ) − min pi (φ)
k k i=1
i=1 i=1
( ) ( )
n ∑
k ∑
k
Let us find the integral of min pi (φ) and − 1
k xui sin (φ) + 1
k yui cos (φ) separately.
i=1 i=1 i=1
First part.
∫2π n
We want to calculate min pi (φ)dφ. Note, that the point Ai will be lowest for all
0 i=1
−−−−→ −−−−→
φ ∈ [α(Ai−1 Ai ), α(Ai Ai+1 )], where α(−
→
v ) is a polar angle of vector −
→
v.
−−−−−→ −−−−−→ −−−−−→
∑
n α(Ai∫Ai+1 ) ∑
n α(Ai∫Ai+1 ) ∑
n α(Ai∫Ai+1 )
So the integral is pi (φ)dφ = yi cos (φ)dφ − xi sin (φ)dφ.
i=1 α(−
−−−−→
Ai−1 Ai ) i=1 −−−−−→
α(Ai−1 Ai ) i=1 −−−−−→
α(Ai−1 Ai )
Integration of sin and cos on segment is simple, this sum can be calculated.
Magically, expression can be simplified further, and the integral equals to minus perimeter of the polygon:
∑
n
− |Ai Ai+1 |.
i=1
Second part.
( ( k ) ( k ) )
∫2π 1 ∑ 1 ∑
We want to calculate − k xui sin (φ) + k yui cos (φ) dφ.
0 i=1 i=1
During the rotation of the polygon the set of underwater vertices u1 , u2 , . . . , uk is changing. In which
angles the set is changing? Note, that if the set of underwater vertices is changing in some angle φ, one of
the vertices Ai lies on the water level in this moment. Vertex Ai can be left or right vertex of the water
level segment.
For all vertices Ai let us find the angles φL,i , φR,i in which Ai is left and right vertex of the water
level segment, respectively. These angles can be found with two pointers method: let us iterate i in
clockwise or counterclockwise order and maintain the set of currently underwater vertices (these vertices
will be consecutive). So we maintain the pointer to vertex j, such that area(Ai Ai+1 . . . Aj ) ≤ s and
area(Ai Ai+1 . . . Aj+1 ) > s (for counterclockwise traversal). This index j can be simply maintained,
−
→ −−−→
because we can maintain the sum of pseudoscalar products Ap × Ap+1 for p ∈ [i, j) to maintain the
Page 8 of 9
ICPC 2023–2024, NERC – Northern Eurasia Finals
St. Petersburg, Novosibirsk, Astana, Kutaisi, December 13th, 2023
area. After that, to find the angle φL,i we should look at the triangle △Ai Aj Aj+1 and find a segment that
divides the triangle into two pieces with given ratio of areas.
So, such event angles φL,i , φR,i where a set of underwater vertices is changing can be found in O(n). After
that, we can sort events and calculate our integral, because on each segment between consecutive events,
∑
k ∑
k
values k1 xui , k1 yui are constant and we should just integrate sin and cos.
i=1 i=1
The total complexity of the solution is O(n log n).
For a single species (s = 1) in the habitat the answer is 1 if tmodl1 = 0 and 0 otherwise.
For two species (s = 2) in the habitat the problem is to count the number of combinations of ia ≥ 0 and
ib ≥ 0 that a × ia + b × ib = t (where a = l1 and b = l2 ). Let ia = ka × b + ja where 0 ≤ ja < b. Iterate over
ja and let rest = t − ja ∗ a. In case restmodb = 0, we should add to the answer number of combinations
of ka and ib that ka × a + ib = rest
b . Or to find number of ka so that ka × a ≤ b . I. e. we need to add to
rest
Page 9 of 9