#P6519. Bodyguard Arrangement in Matrix
Bodyguard Arrangement in Matrix
Bodyguard Arrangement in Matrix
You are given a matrix with n rows and m columns. Each cell in the matrix can either have a bodyguard (represented by 1) or be empty (represented by 0). For each row and each column, a target number of bodyguards is specified. Your task is to determine whether there exists a placement of bodyguards such that every row i has exactly ri bodyguards and every column j has exactly cj bodyguards.
A necessary condition is that the total number of bodyguards in rows equals that in columns, i.e.,
$\sum_{i=1}^{n}r_i=\sum_{j=1}^{m}c_j$
Moreover, by the Gale-Ryser theorem, a sufficient and necessary condition for the existence of such a binary matrix is that for every k from 1 to n,
$\sum_{i=1}^{k}r_i \leq \sum_{j=1}^{m}\min(c_j,k)$
If both conditions hold, output YES
; otherwise, output NO
.
inputFormat
The first line contains an integer T
(T ≥ 3) representing the number of test cases.
Each test case is described as follows:
- The first line contains two integers
n
andm
, denoting the number of rows and columns, respectively. - The second line contains
n
integers:r1, r2, ..., rn
, representing the required number of bodyguards for each row. - The third line contains
m
integers:c1, c2, ..., cm
, representing the required number of bodyguards for each column.
Input numbers are separated by spaces.
outputFormat
For each test case, output a single line containing YES
if there exists a valid arrangement of bodyguards under the given constraints; otherwise, output NO
.
sample
3
3 3
1 2 1
1 2 1
2 2
2 0
1 1
2 2
2 1
1 1
YES
YES
NO
</p>