Professional Documents
Culture Documents
Friendlyrooks
Friendlyrooks
Friendlyrooks
Problem Statement
There are N ! ways to place N rooks on
an N × N chessboard such that no two
rooks attack each other
There is an N × M chessboard. The rows are numbered from 1 to N and the columns are
numbered from 1 to M . (x, y) denotes the tile on the x-th row and the y-th column. You
are given 3 arrays A, B, and C, each of length K.
You can place a rook on (x, y) if Ai · x + Bi · y ≤ Ci for all 1 ≤ i ≤ K. You want to place
as many rooks on the chessboard as possible, while ensuring that no two rooks attack each
other. Formally if a rook is placed on (x, y) and another is placed on (x′ , y ′ ), then both
x ̸= x′ and y ̸= y ′ must be satisfied.
Find the maximum number of rooks you can place on the chessboard, and also construct
one possible way to place these rooks.
Input Format
The first line of input contains three integers, N , M , and K.
The i-th line of the following K lines of input contains three integers, Ai , Bi , and Ci .
Output Format
In the first line, output a single integer k, the maximum number of rooks you can place on
the chessboard.
In the i-th line of the following k lines, output two integers xi and yi , describing that the
i-th rook should be placed on (xi , yi ).
Constraints
• 1 ≤ N, M ≤ 2 · 105
• 1 ≤ K ≤ 100
• −1012 ≤ Ai , Bi , Ci ≤ 1012
Subtasks
1. (20 points) N, M ≤ 9
2. (30 points) N, M ≤ 18
3. (50 points) No additional constraints
4. Sample test cases
Sample Output 1
2
41
22
Sample Input 2
691
420
Sample Output 2
0
Explanation
In sample input 1, you can place rooks only on tiles (2, 1),(2, 2),(3, 1),(3, 2) and (4, 1). There
are only 2 distinct possible values of y such that you can place a rook on tile (x, y), so the
maximum number of rooks you can place on the chessboard without any two rooks attacking
each other is 2. Another possible solution is to place rooks on tiles (3, 2) and (4, 1).
You can place a rook on tile (3, 2) since (−4) · 3 + (−1) · 2 = −14 ≤ −7 and (1) · 3 + (7) · 2 =
17 ≤ 17. You cannot place a rook on tile (1, 1) since (−4) · 1 + (−1) · 1 = −5 ̸≤ −7.