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 . First, we root the tree arbitrarily. Let . We can break into and .
Because must be an ancestor of both and , and where is the sum of the path betwen the 2 nodes and . We can compute for all in with a simple DFS. We also compute where is the number of edges between and in similar fashion.
We perform small to large merging to find an such that , and is minimized.
To accomplish this, we can use small to large merging. For each , we maintain a map of key to value pair of for distinct for all in the subtree of . If there are duplicate we take the minimum .
As we combine the maps of two nodes, we iterate through each key-pair of the smaller size map, search for a key-pair in the larger map, and if this exists we obtain from . Our answer would be minimum over all mergings. During this process we also merge all key-value pairs of the smaller map.
Implementation
Time Complexity:
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!