#C8644. Minimum Moves to Connect Warehouse

    ID: 52649 Type: Default 1000ms 256MiB

Minimum Moves to Connect Warehouse

Minimum Moves to Connect Warehouse

You are given a warehouse with R rooms, each containing a certain number of elves. Additionally, there are C corridors, where each corridor connects two distinct rooms (the corridors are bidirectional). The goal is to determine the minimum number of elves that must be moved so that all the rooms become connected (i.e. there is a path between any two rooms).

Formally, let the rooms be indexed from 1 to \(R\). You are given an array \(elves\) of length \(R\) where \(elves[i]\) represents the number of elves in room \(i+1\) (this value is provided for compatibility with the problem, but is not used in the computation). Also, you are given \(C\) corridors described by pairs \( (u, v) \), indicating that room \(u\) is directly connected to room \(v\). The warehouse is said to be fully connected if, for every two distinct rooms \(i\) and \(j\), there is a path from \(i\) to \(j\).

If there are no corridors (i.e. \(C = 0\)), then it is impossible to connect the warehouse and you should output \(-1\). Otherwise, if the warehouse is already fully connected, then output \(0\). In other cases, suppose the graph consists of \(k\) connected components with sizes \(s_1, s_2, \ldots, s_k\). After sorting these sizes in non-decreasing order, the minimum number of moves required to connect the warehouse is given by:

[ \text{moves} = \sum_{i=1}^{k-1} s_i - (k-1) ]

where each connection between two components requires moving one elf per room in the smaller components (except one room that becomes the junction, hence subtract \(1\) per connection).

Your task is to implement this logic. All input should be read from stdin and the result must be printed to stdout.

inputFormat

The input is given as follows:

R
elves[0] elves[1] ... elves[R-1]
C
u1 v1
u2 v2
...
uC vC

Where:

  • R is the number of rooms.
  • The second line contains R space-separated integers, representing the number of elves in each room (note: these values are not used in the computation).
  • C is the number of corridors.
  • Each of the next C lines contains two integers u and v, which represent a corridor connecting room u and room v.

outputFormat

Output a single integer representing the minimum number of moves needed to connect all the rooms. If there is no way to connect the warehouse (i.e. when C = 0), output -1.

## sample
4
3 2 1 4
3
1 2
3 4
1 4
0