Editorial for An Animal Contest 4 P5 - Neighbourly Neighbourhoods


Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.

Author: sjay05

In summary, this problem asks us to construct a directed graph of N nodes with M edges, such that there are X SCC's (Strongly Connected Components) on the condition that Q pairs (xi,yi) belong to the same SCC.

Consider the edge types for a graph with X SCCs:

  • Edges within an SCC. For an SCC consisting of α nodes (size α), there are a maximum of α(α1) possible edges that can be formed.

  • Edges between SCCs. Consider all (X2) pairs of SCCs. For an SCC with size α and another with size β, αβ edges can be formed between them.

The next step involves choosing X distinct SCCs:

Subtask 1

Since Q=0, we pick the X SCCs to to be {1},{2},,{X1},{XN}. The size of the last SCC needs to be maximized, to maximize the number of edges that can be placed on the first condition listed above.

Subtask 2

Let P be the maximum number of SCCs that can be created from the input. This can be finding the number of connected components of the Q constraints with a DSU. If P<X, output -1. If P>X, the largest PX+1 components (by size) must be considered as 1 SCC, to total X SCCs. The "largest" are being considered to maximize the number of edges to be placed on the first condition listed above.


Let sz[i] be the size of the i-th SCC. For the X SCCs considered, each requires a minimum of sz[i] edges to satisfy the properties of an SCC, unless it is a single node. For example, if one set of nodes were {1,2,,k}, the edges formed would be 12,23,,k1k,k1.

If sz[i]>M, there are not enough edges to satisfy the constraint of M edges, so output -1.

Finally if sz[i]<M, for each SCC with size sz[i] you can add sz[i](sz[i]1)sz[i] more edges, and add edges between SCCs. Note that when constructing edges between SCCs, for each pair of SCCs (suppose SCC a and SCC b), edges must only flow from a node in a to a node in b, or vice versa. Accounting for both directions will unite a and b as 1 SCC, which needs to be avoided.

At this point, if we have already reached our M required edges, we can simply output them and terminate our program. If M is still greater than the number of possible edges that can be added, output -1.

Time Complexity: O(N+QlogN+MlogM)


Comments

There are no comments at the moment.