IOI 2011 - Race

Author: Timothy Gao

Official Analysis (Centroid Decomposition)

Alternative Solution: Small to Large Merging

We are tasked with finding a path with the minimum number of traversed edges such that the path sum is ss. First, we root the tree arbitrarily. Let lca(u,v)=w\text {lca}(u, v) = w. We can break path(u,v)\text {path}(u, v) into path(u,w)\text {path}(u, w) and path(v,w)\text {path}(v, w).

Because ww must be an ancestor of both uu and vv, sum(u,w)=sum(u,root)sum(w,root)\text {sum}(u, w) = \text {sum}(u, root) - \text {sum}(w, root) and sum(v,w)=sum(v,root)sum(w,root)\text {sum}(v, w) = \text {sum}(v, root) - \text {sum}(w, root) where sum(a,b)\text {sum}(a, b) is the sum of the path betwen the 2 nodes aa and bb. We can compute sum(i,root)\text {sum}(i, root) for all ii in O(N)O(N) with a simple DFS. We also compute dist(i,root)\text {dist}(i, root) where is the number of edges between ii and rootroot in similar fashion.

We perform small to large merging to find an lca\text {lca} ii such that sum(u,root)+sum(v,root)2sum(i,root)=s\text {sum}(u, root) + \text {sum} (v, root) - 2 \cdot \text {sum}(i, root) = s, and dist(u,root)+dist(v,root)2dist(i,root)=s\text {dist}(u, root) + \text {dist}(v, root) - 2 \cdot \text {dist}(i, root) = s is minimized.

To accomplish this, we can use small to large merging. For each ii, we maintain a map of key to value pair of sum(root,j):dist(root,j)\text {sum}(root, j) : \text {dist}(root, j) for distinct sum(root,j)\text {sum}(root, j) for all jj in the subtree of ii. If there are duplicate sum(root,j)\text {sum}(root, j) we take the minimum dist(root,j)\text {dist}(root, j).

As we combine the maps of two nodes, we iterate through each key-pair (sums,dists)(sum_s, dist_s) of the smaller size map, search for a key-pair suml=ssumssum_l = s - sum_s in the larger map, and if this exists we obtain dists+distldist_s + dist_l from sumlsum_l. Our answer would be minimum dists+distldist_s + dist_l over all mergings. During this process we also merge all key-value pairs of the smaller map.

Implementation

Time Complexity: O(Nlog2N)\mathcal{O}(N\log^2N)

The log factors come from small-to-large merging and the map operations.

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<ll, ll> pii;
#define pb push_back
#define f first

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!