#K77097. Graph Load Balancing Operations

    ID: 34788 Type: Default 1000ms 256MiB

Graph Load Balancing Operations

Graph Load Balancing Operations

You are given an undirected graph with n nodes and m edges. Each node has an initial load. In one operation, for each edge connecting node u and v, if the loads differ, a load transfer is performed: a value of \( \frac{a_u - a_v}{2} \) is moved from the higher loaded node to the lower loaded neighbor. The task is to determine the minimum number of operations required to make the loads of all nodes equal. If it is impossible, output -1.

Note: The transfer for each edge is applied simultaneously in one operation round. The process is repeated for at most \( n \) rounds. If even after these rounds the loads do not all become equal, consider it impossible.

Input constraints: It is guaranteed that the graph does not necessarily need to be connected, and there might be test cases with no edges.

inputFormat

The input is read from standard input (stdin) and has the following format:

T
n m
a[1] a[2] ... a[n]
u1 v1
u2 v2
... (m lines for edges)
... (repeated for T test cases)

Where:

  • T: Number of test cases.
  • n: Number of nodes.
  • m: Number of edges.
  • a[i]: The load on the i-th node.
  • u v: An undirected edge between nodes u and v. Nodes are 1-indexed.
  • </p>

    outputFormat

    For each test case, output one line containing a single integer: the minimum number of operations required to balance the loads across all nodes, or -1 if it is not possible.

    ## sample
    1
    3 3
    3 1 2
    1 2
    2 3
    3 1
    
    2
    

    </p>