Official

D - Valid Output for DSU Problems Editorial by evima


Consider the conditions on the obtained \(A\) when the order of adding edges is fixed.

Let \(k\) be the number of \(\text{1}\)s in \(A\). Let \(c\) denote the number of pairs \(i,j(1 \leq i<j \leq N)\) such that \(i\) and \(j\) are connected. Let \(x\) be the value of \(c\) just before \(c\) first becomes at least \(k\), and \(y\) be the value of \(c\) just after.

Then, the condition on \(A\) is that the number of \(\text{0}\)s to the left of the \((x+1)\)-th \(\text{1}\) is at least \(y-k\). Also, the number of operations needed to make \(B\) a special string is the number of operations needed to move \(\text{0}\)s to the right of the \((x+1)\)-th \(\text{1}\) to the left until the condition is satisfied.

When we fix the value of \(y\), we find that \(x\) should be as large as possible while being less than \(c\).

If the size of the connected component created by merging when \(c\) becomes at least \(k\) is \(N-n\), and \(m\) is the number of pairs of connected vertices not included in it, then \(y\) is determined, and the optimal \(x\) is also determined. By using DP to find the minimum \(n\) such that \(n\) vertices can be used to make \(m\) pairs of connected vertices, and maintaining the cumulative sum of the number of \(\text{1}\)s to the left of each \(\text{0}\), etc., we can find the number of operations needed for each \(n,m\).

Consider the time complexity. The way to partition \(N-n\) vertices so that \(x\) is optimal has monotonicity with respect to \(m\), so by two-pointer technique, it can be computed in \(O(N^3)\) for each \(n,m\). Also, everything else can be computed in \(O(N^3)\).

posted:
last update: