Solution for USACO 2026 First Contest, Silver, P2
Preface
这是一篇英文题解。This is an English solution.
Solution
Build an undirected graph with the given constraints, connecting vertices and with an edge weighted . After that, consider every connected component independently.
Case 1: The connected component has at least edges, i.e. it’s not a tree.
In this case, there is a fixed solution if and only if there is an odd cycle in the graph. Conversely, every even cycle has a redundant edge. For example:
where is redundant, since we could know the value of is with the previous 3 equations. Specifically, when we detect an even cycle, we have to check if the weight on the redundant edge doesn’t contradict other edges on the cycle (check if in the example).
If no contradiction in an even cycle is detected and the graph doesn’t have an odd cycle, remove the redundant edges and treat it as a tree (Case 2). Otherwise, the solution for every vertex is fixed. We could simply calculate one value of on a vertex in an odd cycle, then let that vertex be the root of a spanning tree of the graph, and we could calculate the rest values via the spanning tree. Make sure the constraints of the edges which aren’t on the spanning tree are satisfied, then check whether is true for each vertex.
For implementation, it’s convenient to find a DFS-tree of the graph first to detect all odd and even cycles.
Case 2: The connected component has edges, i.e. it’s a tree.
In this case, there isn’t a fixed solution for the set of equations. Let the root of the tree be . We’re able to generate a solution set for the tree after we determine the value of . Assume we’ve already known that , and let , where is the parent of vertex on the tree and is the weight of the edge connecting and . It’s easy to verify that, is satisfied if and only if:
- , if the depth of is an odd number.
- , if the depth of is an even number.
We define the depth of vertex as , and the depth of is .
Now, our goal becomes choosing a value of that is covered by the maximum number of segments. This problem could be solved by simply increasing the values at all positions within the range by for each segment using a difference array, and then finding the position with the maximum value as the result. We need to discretize the values of the endpoints of the segments before processing.
The time complexity of the solution is , since we have to sort the elements in Case 2.
