Preface

这是一篇英文题解。This is an English solution.

Solution

Build an undirected graph with the given mm constraints, connecting vertices xx and yy with an edge weighted zz. After that, consider every connected component independently.

Case 1: The connected component has at least V|V| 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:

{a+b=k1b+c=k2c+d=k3a+d=k4\begin{cases} a + b = k_1\\b+c=k_2\\c+d=k_3\\ \color{gray}a+d=k_4 \end{cases}

where a+d=k4a+d=k_4 is redundant, since we could know the value of a+da+d is k1+k3k2k_1+k_3-k_2 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 k4=k1+k3k2k_4=k_1+k_3-k_2 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 aia_i 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 liairil_i\leq a_i\leq r_i 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 V1|V|-1 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 rtrt. We’re able to generate a solution set for the tree after we determine the value of arta_{rt}. Assume we’ve already known that art=ca_{rt}=c, and let wu=Wwfauw_u=W-w_{fa_u}, where faufa_u is the parent of vertex uu on the tree and WW is the weight of the edge connecting faufa_u and uu. It’s easy to verify that, luaurul_u\leq a_u\leq r_u is satisfied if and only if:

  • wurucwuluw_u-r_u\leq c\leq w_u-l_u, if the depth of uu is an odd number.
  • luwucruwul_u-w_u\leq c\leq r_u-w_u, if the depth of uu is an even number.

We define the depth dd of vertex uu as dfau+1d_{fa_u}+1, and the depth of rtrt is 00.

Now, our goal becomes choosing a value of cc 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 11 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 O(nlogn+m)\mathcal{O}(n\log n+m), since we have to sort the elements in Case 2.