Explanation
For the first few test cases where , we can solve the problem by constructing an MST with being the weights. If we let and , will be minimized when is minimized.
To solve the problem completely, we will have to minimize the product of those two sums, . The solution space contains all possible MSTs with their respective and values. We can view each of those possible solutions as a 2D-point . There exists a curve such that every point on it has the same value. As an inverse proportion function, it is convex, so the best solution must lie somewhere on the left-most curve, i.e. on the lower convex hull. Therefore, it suffices to check all points on the lower convex hull of our solution space to find the minimal value. Nevertheless, we cannot really calculate the convex hull since it would require all points to be known. Instead, we use another approach below.
At the beginning, we choose two points on the lower convex hull, and , as our starting points for our search. should be the point where we minimize and where we minimize . We then want to find a point which is left-most from line . The area of the triangle is proportional to the distance between the line and the point , given is constant. Therefore, we only have to find out the triangle with maximum area. Using the cross product, we get . Note that is constant and can be ignored. Thus, is proportional to . As our goal was to maximize , we should here minimize instead. This can be done by taking this value as the weight of our MST algorithm and then build the MST. The result would be our new point . If is on the right side of vector (thus on the left side of line ), it is also on the convex hull. We then use Divide-and-Conquer and solve the same problem with either points , or , . For each of these points, we update the current best solution if the new point is better. Otherwise, if is on the right side of line , we do not have to search further with since it is not on the lower convex hull anymore.
Since and are positive integers, the lower convex hull between and consists of points. For each of those points, we run Kruskal's algorithm in . Therefore, the total time complexity is . This suffices for the given test cases.
C++
Implementation
#include <bits/stdc++.h>using namespace std;using ll = long long int;using pii = pair<int, int>;Code Snippet: DSU (Click to expand)struct Edge {int x;int y;
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!