Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
62 views8 pages

Nerc 2021 Tutorial

The document outlines problems from the ICPC 2021–2022 Northern Eurasia Finals, detailing various algorithmic challenges including admissible maps, budget distribution, connecting points, deletive editing, even split, fancy stack, and global warming. Each problem is accompanied by its author, a brief description of the approach to solve it, and key observations or methods used. The solutions involve techniques such as dynamic programming, binary search, and geometric algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views8 pages

Nerc 2021 Tutorial

The document outlines problems from the ICPC 2021–2022 Northern Eurasia Finals, detailing various algorithmic challenges including admissible maps, budget distribution, connecting points, deletive editing, even split, fancy stack, and global warming. Each problem is accompanied by its author, a brief description of the approach to solve it, and key observations or methods used. The solutions involve techniques such as dynamic programming, binary search, and geometric algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

ICPC 2021–2022, NERC – Northern Eurasia Finals

St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

Problem A. Admissible Map


Problem author and developer: Ilya Zban

Let’s call any string of shape “RLRL...RL” trivial.


Lemma: any non-trivial string has at most one constitution as an admissible map.
Proof: let’s consider string s0 s1 . . . s|s|−1 , and i be a first even number such that si si+1 6=“RL”. There can
be a few cases:

• si =“L”. String s doesn’t have a constitution as an admissible map, as either the i-th symbol will be
on the left edge of the matrix (and its edge isn’t directed to any other cell), or it points to the left,
to “RL” so there are two incoming edges to neighboring “L” (or it points out of the matrix).

• si =“U”. String s doesn’t have a constitution as an admissible map, as either the i-th symbol will be
on the upper edge of the matrix (and its edge isn’t directed to any other cell), or it points to some
pair “RL”, that should be matched to each other.

• si =“R”. As si+1 6= “L”, the only incoming edge to i-th cell can be “U”. And we can notice that it can
only be the first “U” in the string, as otherwise the first “U” would point either outside of the matrix
|s|
or to some “RL” pair. So, if sj is the leftmost “U”, string s can only be constituted as j−i ×j−i
map.

• si =“D”. Let’s say that k = i if si+1 6= “L”, and otherwise take k as maximal number such that
si+1 . . . sk =“LLL..L”. Substring si . . . sk should be in same row of matrix, and as sk+1 6=“L”, by
same argument as above we can see that the first “U” in the string should point to sk . So, string s
|s|
can only be constituted as j−k × j − k map.

So, the shape n×m of a matrix for any non-trivial substring sl sl+1 . . . sr is determined only by the position
of the first “U” after l. We can compute an array ml meaning that any substring sl sl+1 . . . sr should be
constituted as r−l+1
ml × ml matrix. This array can be computed in linear time directly from proof.
Using ml we can iterate over all r = l + t · ml for all t, and check all substrings sl sl+1 . . . sr . We need to be
able to quickly determine if substring si . . . si+ml −1 can be a top, middle or a bottom row of constituted
matrix. It can be done in O(1) time.
Let’s consider the case of the middle row (other cases are similar). We want to check that no edge from
si . . . si+ml −1 goes outside of the matrix and that each cell has exactly one incoming edge. First, we need to
check that si 6=“L” and si+ml −1 6=“R”. Conditions on incoming edges can be tested using hashes. We choose
a hash base x, and build 4 arrays ac0 . . . ac|s|−1 (c in “ULDR”) such that aU
j = x if sj =“U”, aj = x if sj =“D”,
j D j

aR j+1 if s =“R” and aL = xj−1 if s =“L”, and all other values are zero. Then we can see that each
j = x j j j
i−1
P D i+l−1 i+2m−1 i+l−1
cell from si . . . si+ml −1 has one incoming edge if xml −ml x.
P L
(at +aR U =
P P t
at + t )+x at
t=i−m t=i t=i+m t=i
This check can be done in constant time using a precomputed array of prefix sums.
Using these checks we can iterate over all non-trivial substrings, test them and add missed trivial strings.
This solution works in O(s2 ).
|s|
We can further notice that for each l we iterate over all possible m l
possible r-s with step ml . We can count
all l that have both the same ml and l mod ml together, as we just do a lot of duplicated work in that
s √
case. This optimization gives us a very fast solution that works in O( m · min(cntm , m)) = O(s s) in
s
P
m=1
worst case (here cntm is the number of different remainders l mod ml for each m).

Page 1 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

Problem B. Budget Distribution


Problem author and developer: Pavel Kunyavskiy
Let’s first solve a single-topic problem. If there are no items that have too much assigned money (more
they should have at the end, including unassigned money), the answer is 0. Otherwise, it’s not important
to which item money is assigned, if not giving too much money to any of the items. So, with a fixed set
of items already having too much money, non-optimality function is linear-fractional in terms of extra
money, i.e it has the form ax+b
cx+d . Also, it is easy to check that the derivative is increasing (it’s negative
and getting closer to zero), so overall the function is convex piecewise-linear-fractional function.
To solve the full problem, we need to find a way to combine solutions for different topics. Let fi be non-
optimality function for i-th topic. In fact, we need to find the function f (x) = P min fi (xi ). As would
xi =x,xi ≥0
be shown later, this function is convex piecewise-linear-fractional too, with a linear number of pieces.
To make a set of xi locally-optimal, it should be impossible to find a pair of indices i and j, such that
decreasing xi a bit, and increasing xj a bit would decrease the function. In fact, this means that all left
derivatives should be less (greater by absolute value, as they are negative), than all right derivatives.
Intuitively, if we think about the continuous process of distributing money, it should work like this: give
next infinitely small amount of money to all topics with smallest derivatives (those, who are decreasing
the fastest), in such proportion that their derivatives would be still the same. And the derivative of the
resulting function in that point is equal to that minimum of the right derivatives.
So, let’s construct a function by sweeping a line over its derivative. Each piece of the topics’ function is
working as “at this range of the derivatives, you also need to add this function”. We know derivatives at
each point, where switch from one piece to another happens, and the piece has a unique point with such
derivative. So the only remaining part is to explicitly find the function for each part, when the set of
topics we are giving money to is known.
a2
For convenience, let fi (x) = x−b
i
i
+ci . Any linear-fractional function with negative derivative can be written
in such form. Intuitively, bi and ci are coordinates of the hyperbola center, and ai is just decreasing speed
factor. This form is convenient, as bi and ci can be just thrown away, as ci only shifts resulting value by
a2
constant, and bi only shifts argument by constant. So we can find the result for functions of the form xi ,
and then just shift it, to make value and derivative in a point where it’s connected to the previous part
correct.
For these kinds of functions, making derivatives same, means that xi
xj = ai
aj for all pairs of i and j. That
( ai )2
P
means xi = Pai x.
ai And the total function is x .

Problem C. Connect the Points


Problem author and developer: Dmitry Yakutov

There are a lot of ways to solve the problem.

1. Brute Force. Take all X- and Y-coordinates of given points and build a “grid” of nine points. Take
all 18 segments between them and iterate over all subsets of these segments. Choose the best one.

2. Deal with “cases”. Mark three points with label sorted by X-coordinate. Then order points by Y-
coordinate and watch the labels. There are six different orderings. It is possible to build the optimal
set of segments for each ordering.

3. Median point. Let xm be median X-coordinate among all the points and ym be median Y-
coordinate. M = (xm ; ym ) is the median point. Note that M can either be in the input set or
not. It is provable that you can connect all three points with M in the shortest way and output the
resulting set of segments.

Page 2 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

4. Median segment. Let xm be median X-coordinate as before and ymin and ymax be minimum and
maximum Y-coordinates. Take the segment from (xm ; ymin ) to (xm ; ymax ) and connect all three
points with this segment by horizontal segments. It is also provable that such a set of segments is
correct.

Problem D. Deletive Editing


Problem author: Dmitry Yakutov; problem developer: Roman Elizarov

This problem can be solved in a straightforward way. The key observation is that the order in which the
letters are called out does not matter in this game. We only need to know how many times each letter is
called out in order to go from the initial word s to the final word t.
So first, let us compute the number of occurrences of each letter from ‘A’ to ‘Z’ in both words s and t.
Let’s call them sa and ta for each letter a. Using these numbers, we can calculate how many times each
letter shall be called in order to get a chance of getting to t. That is sa − ta times for each letter a.
If sa − ta < 0 for any letter a, then the answer is “NO”.
Otherwise, there is a chance for a positive answer. However, we also need to verify that the order of
the letters in t is correct. The easy way to verify it is to simulate the game, dropping the first sa − ta
occurrences of each letter a, and then compare the result with t.

Problem E. Even Split


Problem author and developer: Egor Kulikov

First, let’s find what is the minimal possible length of the longest segment. Using binary search on said
length suppose we need to test if len is enough. We can show that it is necessary and sufficient if we
can find n segments of length len (maybe intersecting) that cover the whole of Segmentland that can be
bijected to n houses so that corresponding segment contains the corresponding house. This can be done
greedily going from left to right and always trying to fit the next segment in the rightmost way so that
we still cover some prefix of Segmentland and the corresponding house.
Now we also need to find the maximal possible length of the shortest segment. This is done similarly with
binary search, only now we want to find segments of the same length that fit into Segmentland without
intersection, and in our greedy algorithm we will fit them in leftmost way.
Given these two lengths, min and max, it can be shown that we can find a subdivision of Segmentland
that adheres to these limits. One way to find such a subdivision is this:

• For i ∈ 0 . . . n let’s have two parameters, ci ≤ di , which means that the corresponding dividing point
lies somewhere between ci and di . We calculate those from left to right starting with c0 = d0 = 0,
and ci+1 = max(ci + min, ai+1 ), di+1 = min(di + max, ai+2 ) (we assume an+1 = l).
• For i ∈ 0 . . . n let’s have ansi as an actual boundary. We will calculate it from right to left, starting
with ansn = l, and on each step we will select any point from [ci , di ] that is between min and max
distance from ansi+1 (it is easy to see there will always be at least one such point).
• Now we have an answer — si = ansi−1 , fi = ansi .

Problem F. Fancy Stack


Problem author: Dmitry Gozman; problem developer: Gennady Korotkevich

Let’s call the blocks on the even positions big (b2 , b4 , . . . , bn ), and the blocks on the odd positions small
(b1 , b3 , . . . , bn−1 ).

Page 3 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

First, assume that the block sizes are distinct. We’ll process the blocks in decreasing order of size (i.e.,
let a1 ≥ a2 ≥ . . . ≥ an ). To count the stacks, we will use dynamic programming.
Let fi,j be the number of ways to put i biggest blocks into their places so that j of these blocks are big,
and i − j of these blocks are small. As a base case, f0,0 = 1. We’ll implement it as a forward DP, and to
make transitions for the i + 1-th block we will decide whether it’s big or small.
If the i + 1-th block is big, its position in the stack is determined uniquely (specifically, it’s bn−2j ). Hence,
we make a transition to fi+1,j+1 .
If the i + 1-th block is small, there are max(j − 1, 0) + [j = n2 ] possible places for small blocks (between
any two big blocks, and at the top of the stack if all big blocks have been placed), out of which i − j
are already occupied. Note that all these potential places will be available for all future (smaller) small
blocks. Hence, it doesn’t matter which particular place we occupy with the i + 1-th block. We make a
transition to fi+1,j with coefficient (max(j − 1, 0) + [j = n2 ]) − (i − j).
Now, if we allow blocks to have equal sizes, we can just process the blocks in groups of the same size —
again, in decreasing order of size. In each group, at most one block can be large (since all big blocks must
have distinct sizes). This way, we still have just two transitions from any DP state, this time with both of
them using binomial coefficients — coming from the fact that we can choose any valid unoccupied places
for small blocks.
Alternatively, instead of splitting the blocks into groups explicitly, we can keep the solution from the “all
distinct” case, and only allow the last block in each group to be big (that is, block i can only be big if
ai > ai+1 ).
The time complexity of this solution is O(n2 ).

Problem G. Global Warming


Problem author and developer: Nikolay Budin

Let’s do a sweep plane algorithm from top to bottom. We will maintain connected components for points
that are higher than the plane and areas of surfaces for these components. When the sweep plane meets
a new point, we iterate over its neighbors that are higher than the plane and unite their connected
components with the new point. In order to store connected components, you may use DSU.
Now, let’s handle areas. Consider a face with vertices a, b and c. If the face is horizontal, we will add its
area to the area of a component when the sweep plane reaches it. Otherwise, suppose za ≤ zb ≤ zc and
the current high of the sweep plane is s. Then the area of a part of the face that is higher than the sweep
plane is:
R zc
z=s l(z) dz
area(s) =
sin(α)
Where α is an angle between the plane of the face and a horizontal plane. And l(z) is the length of a
section of the face by a horizontal plane on high z. Function l(z) is linear on segments [za , zb ] and [zb , zc ].
So, function area(s) is a quadratic on the same segments. So, we can maintain the sum of such quadratic
functions over all faces of one connected component. And when we meet a new point, we iterate over all
faces that contain this point and modify the quadratic function for that face.
Finally, when the sweep plane reaches the high of some query, we look at the connected component of the
point in the query.

Problem H. Heroes of Might


Problem author: Nikolay Budin; problem developer: Borys Minaiev

The full editorial of this problem could be pretty long, so we just provide some key ideas required for the
solution without going into much detail.

Page 4 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

Let’s first discuss the slow solution, which works when the total number of rounds is not big. For each
group of peasants, we can generate an array of integers ki — number of peasants killed on i-th attack of
this group. For example if damage is equal to 15, the health of each peasant is 10, and there is a group of
4 peasants, the corresponding array is equal to [1, 2, 1].
After constructing an array for each group, we can “merge” them into one big array in a way which
preserves the initial ordering of elements in each array. Such a merged array corresponds to some ordering
in which dragon attacks groups. Optimal merging should maximize the sum of all prefix sums of the
generated array.
How to merge arrays? Let’s split each array into several continuous intervals, and for each of them calculate
ai — sum of elements in the segment divided by the length of the segment. Over all possible splits we
choose one with special properties:
• a1 > a2 > ... > an
• (a1 , a2 , ..., an ) — lexicographically largest
Such a split could be computed greedily. First, find the prefix with largest a1 , cut it, recursively find other
prefixes.
There is also a nice geometrical interpretation of such a split. We can draw points (i, j≤i kj ), and find
P
the upper convex hull of them. Each segment of the convex hull corresponds to the segment in the optimal
array split.
It could be proven that each segment of the split could stay continuous inside optimally merged arrays.
Moreover, to determine the order in which segments for different groups should be merged, we can just
sort them by ai .
It also could be proven that the optimal split has O(log) segments.
The only question left is how to build such segments for larger constraints. We need to find a convex hull
of points (i, b d·i
hp c). There are different possible approaches. One of the easiest is to use continued fractions.
There is a detailed description of the algorithm for finding the convex hull of lattice points under the line
in https://cp-algorithms.com/algebra/continued-fractions.html.
We also need to handle the last point carefully as it doesn’t follow formula b d·i
hp c.

Problem I. Interactive Treasure Hunt


Problem author and developer: Pavel Marvin

Let’s notice that pairs of points (x1 , y1 ), (x2 , y2 ) and (x1 , y2 ), (x2 , y1 ) give the same results for all possible
SCAN requests. So we will assume that x1 ≤ x2 and y1 ≤ y2 , and then check both these pairs using three
DIG requests.
First, let’s make SCANs in points (1, 1) and (1, m).

A = SCAN(1, 1) = (x1 − 1) + (x2 − 1) + (y1 − 1) + (y2 − 1) (1)


B = SCAN(1, m) = (x1 − 1) + (x2 − 1) + (m − y1 ) + (m − y2 ) (2)

From these values we can find sums:

A + B + 6 − 2m
Sx = x1 + x2 = (3)
2
A − B + 2 + 2m
Sy = y1 + y2 = (4)
2
Sy
Now let’s make SCAN in points (b Sx
2 c, 1) and (1, b 2 c).

Page 5 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

Sx
C = SCAN(b c, 1) = (x2 − x1 ) + (y1 − 1) + (y2 − 1) (5)
2
Sy
D = SCAN(1, b c) = (x1 − 1) + (x2 − 1) + (y2 − y1 ) (6)
2

From these values we can find the differences:

Dx = x2 − x1 = C − Sy + 2 (7)
Dy = y2 − y1 = D − Sx + 2 (8)

Now we can find values

S x − Dx
x1 = (9)
2
S x + Dx
x2 = (10)
2
S y − Dy
y1 = (11)
2
S y + Dy
y2 = (12)
2

Finally, we can DIG in cell (x1 , y1 ). If we find the treasure, then the second one must be in cell (x2 , y2 ). If
not, then the treasures are in the cells (x1 , y2 ) and (x2 , y1 ).

Problem J. Job Lookup


Problem author: Vitaly Aksenov; problem developer: Mikhail Dvorkin

This problem can be solved by dynamic programming “over subsegments”.


Consider a subproblem for a segment of people [i, j]. We want to arrange them as a subtree of the global
hierarchy tree in the optimal way. Let’s denote aij to be the minimal possible communication cost induced
by the edges in this subtree. That is, each communication path that costs cuv · duv can be fragmented as
the sum of duv payments of size cuv being paid in each edge of the path. So in our dynamic programming
value aij we will only consider the part of communication cost that is paid in the edges of the constructed
subtree.
To calculate aij simply iterate over all possible root candidates k ∈ [i, j]. For a specific k the communication
cost in the subtree [i, j] is composed of: ai,k−1 , ak+1,j , the communication cost paid in the edge from k to
its left child (if any), and the communication cost paid in the edge from k to its right child (if any).
The communication cost paid in the edge from k to its left child is the sum of cuv over all pairs (u, v)
such that u is in [i, k − 1] and v is not (indeed, these are all pairs of people that do pay in this edge). This
value is simply a sum of two subrectangles in the matrix c. The same obviously applies to the cost in the
edge to the right child.
If the prefix sums (or a similar data structure) is precalculated for the matrix c, the cost for specific k
can be calculated in O(1) time, the value of aij — in linear time, and the entire problem — in cubic time.
Some information about the origin and the relevance of the problem can be found in the SplayNet paper,
section III A: https://www.univie.ac.at/ct/stefan/ton15splay.pdf

Page 6 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

Problem K. Kingdom Partition


Problem author: Maxim Akhmedov; problem developer: Niyaz Nigmatullin
Let us start by writing down a matrix of coefficients applied to the cost of an edge in the resulting
functional depending on possible part belonging of its endpoints:

A B C
A 2 0 1
B 0 2 1
C 1 1 0

Table 1. Desired coefficient matrix

The shape of the problem hints that it is somehow related to minimum cut, but the standard minimum
cut-driven technique expresses the division of vertices into two parts, while we are asked about dividing
vertices into three parts A, B and C. The main trick is to perform a frequently appearing skew-symmetric
transformation of a graph. Replace each vertex v with two vertices v1 and v2 and each edge uv of cost l
with two edges u1 v2 and u2 v1 of the same cost l.
Consider an arbitrary cut (S, T ) of a new graph into two disjoint vertex sets S and T . Each vertex v of
the original graph may be seen as being in one of four states SS, ST , T S and T T depending on whether
each of v1 and v2 belongs to S or T . Write down a similar matrix of possible values of the coefficient
applied to the cost of an edge (of the original graph) in the cut value cut(S, T ):

ST TS SS TT
ST 2 0 1 1
TS 0 2 1 1
SS 1 1 0 2
TT 1 1 2 0

Table 2. Coefficient matrix from cuts in a skew-symmetric graph

Note that the desired matrix is a submatrix of the matrix above. This “coincidence” hints that we must
restrict vertex a to be an ST -vertex and vertex b to be a T S-vertex. Note that this can be done by
connecting a source vertex s with a1 and b2 , and connecting a2 and b1 with a sink vertex t using edges of
infinite capacity and considering s − t cuts in the resulting graph.
The last remaining issue is that we have distinct classes of SS and T T vertices. It turns out that the
minimum cut may always be chosen such that there are no T T vertices; indeed, make all T T vertices be
SS vertices. As a result, no edge coefficient would increase; moreover, some SS − T T edge coefficients
would become SS − SS edges, decreasing their coefficients from 2 to 01 .
Combining everything together, we get a solution that constructs a skew-symmetric graph, finds a
minimum cut in it using any appropriate maximum flow algorithm (e.g. Dinic algorithm), and then
recovers the desired partition as A = ST , B = T S and C = SS ∪ T T .
1
An educational remark. The last result is a special case of a generic cut function submodularity property: if cut(X) is a
value of the cut between X and V \ X, then

cut(X ∩ Y ) + cut(X ∪ Y ) ≤ cut(X) + cut(Y ).

Now apply this property to X := S and Y := T 0 where T 0 is a set of vertices symmetric to the vertices in T (i.e. v10 = v2
and v20 = v1 ), and obtain the previous result.

Page 7 of 8
ICPC 2021–2022, NERC – Northern Eurasia Finals
St. Petersburg, Almaty, Barnaul, Minsk, Yerevan, April 13th, 2022

Problem L. Labyrinth
Problem author: Michael Mirzayanov; problem developers: Sergey Melnikov, Michael Mirzayanov
Let the required two paths have the form:

• s = u1 , u2 , . . . , ux , t;

• s = v1 , v2 , . . . , vy , t.
Let us show that there is always a pair of required paths such that the vertices ux and vy (that is, the
penultimate vertices of the paths) lie in different subtrees of any depth-first search tree rooted at s. This
only applies when both vertices are different from s.
There is a separate corner case in this problem when ux = s or vy = s. Just remember about it, it is easy
to handle it in code.
Indeed, let’s take t such that the distance from s to t is minimal.
Suppose this is not the case and there is a depth-first search tree such that vertices ux and vy are in the
same DFS subtree rooted at s. But since t is the answer, there are two distinct vertex-disjoint (except
vertices s and t) paths: u1 , u2 , . . . , ux , t and v1 , v2 , . . . , vy , t.
Since u1 6= v1 , then at least one of these paths starts not in the subtree where ux and vy are located.
Without loss of generality, let this path be u1 , u2 , . . . , ux , t. Find the first vertex in it (minimum index
j) such that uj belongs to the path in the DFS tree from s to ux . Thus, we have built a pair of non-
intersecting paths (from s to uj ) that end at the same vertex, and this vertex is closer to s than t. We
get a contradiction with the fact that the distance from s to t is minimal.
Thus, it is enough to run a depth-first search and choose such a vertex as t, such that:

• let the DFS parent of vertex t be vertex ux ,

• t has an edge from some vertex vy , which in this DFS tree is in a different DFS subtree than t
relative to the root s (or vy = s and ux 6= s).

These paths in DFS tree (from s to ux and from s to vy ) will induce the required paths.

Page 8 of 8

You might also like