Explanation
Without loss of generality, let's assume we've already computed the best beauty values for all of vertex 's neighbors.
Let store and and store the beauty values of all vertices adjacent to .
For example, we'll set
Let's say that we select , which gives us a beauty of . Can we do better than this?
Intuitively, for any that we choose to be 's beauty value, if there's more elements that are greater than this , making as small as possible would be more optimal (increasing differences for these elements) and vice versa. Note that in a case where the number of greater beauty values is the same as the number of smaller beauty values, setting to the minimum or maximum will never decrease the answer. Moving will always increase the distance for the other end of the beauty values.
Why does this work?
Choosing the median minimizes the sum of absolute deviation, so we'd want to get as far away from the median as possible.
This observation is all we need. Since setting to or is always optimal, we'll handle this through DP.
If stores the maximum sum of beauty values at the subtree rooted at when 's "beauty type" is . Since vertex can only take two values, will be equal to when 's beauty value is and when 's beauty value is .
Our transitions are:
This essentially means:
If has the beauty :
beauty if has a beauty value of , beauty if has a beauty value of )
If has the beauty :
beauty if has a beauty value of , beauty if has a beauty value of )
Implementation
Time Complexity:
C++
#include <algorithm>#include <iostream>#include <vector>using std::cout;using std::endl;using std::pair;using std::vector;vector<vector<int>> adj;
Java
import java.io.*;import java.util.*;public class ParsasHumongousTree {private static List<List<Integer>> adj = new ArrayList<>();private static int[] l, r;private static long[][] dp;public static void main(String[] args) {Kattio io = new Kattio();
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!