Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
hackercup / 2021 /finals /vacation_sol.md
wjomlex's picture
2021 Problems
d3f4f72 verified
|
raw
history blame
2.89 kB

Note that the network of cities and roads form a tree (which we consider to be rooted at node (1)), and that a vacation using (t) teleports is equivalent to a set of (t+1) simple paths on the tree, with ore-naments collected from all nodes present in at least one path.

We'll begin by considering a different variation of this problem, in which each path used incurs some constant penalty of (P) ore-naments (such that, if (o) ore-naments are collected using (p) paths, the final ore-nament count (x) will be (o - p * P)). In this variation, let's maximize (x), breaking ties by minimizing (p).

This variation is solvable using DP, letting (DP_{i,j}) be the optimal pair of ((x, p)) for node (i)'s subtree, such that (j) paths are ongoing between node (i) and its parent (with those (j) paths not included in (x) and (p)). The overall answer will then be (DP_{1,0}). We can observe that values of (j) up to (2) are relevant (as there must be an optimal set of paths such that no tree edge is part of (3) or more paths). This means there are only (O(N)) states, which are all possible to evaluate in linear time. A key aspect of the implementation is only counting each path and its penalty once, for example only at its topmost node (when it doesn't continue from node (i) up to its parent, due to either ending there or feeding into two of (i)'s children).

To now solve the original problem, we can employ a technique which goes by various names, including "parameter search" or the "Aliens optimization" — its workings and requirements are described in greater detail here.

In short, we'll binary search for the largest per-path penalty (P) (between (0) and (\sum_{i=1}^N C_i))) which results in an ore-nament count of (o) (excluding subtraction from path penalties) of at least (K). Note that (o = x + p * P). We can do so because:

  • As (P) increases, the path count (p) and corresponding ore-nament count (o) decrease or stays equal
  • If we define a function (F(p)) as the maximum ore-nament count (o) for a given path count (p), (F(p)) is concave (the more paths are used, the more diminished are their returns)

Let (o_1) and (p_1) be the optimal ore-nament and path counts for the penalty (P) produced by the binary search, and (o_2) and (p_2) be the corresponding counts for penalty (P+1). Note that (o_2 \lt K \le o_1) and (p_2 \lt p_1). The minimum number of paths required to collect (K) ore-naments is then somewhere in the interval ((p_2, p_1]). In particular, we can linearly interpolate between ((o_1, p_1)) and ((o_2, p_2)) to compute our final answer as (p_2 + \lceil(K - o_2)(p_1 - p_2) / (o_1 - o_2)\rceil + 1).

The time complexity of this solution is (O(N * \log(\sum_{i=1}^N C_i))).