Domino Piling (50A) looks like a tiling or search problem at first, and you might be tempted to try placements one by one. In fact the answer is a single division. The interesting part is proving why that division is always achievable.
The problem in short
You have a rectangular board of M × N squares (1 ≤ M ≤ N ≤ 16) and an unlimited supply of 2 × 1 dominoes, which can be rotated. Dominoes cannot overlap and must lie entirely on the board. What is the maximum number of dominoes you can place?
Full statement: Codeforces 50A – Domino Piling.
Upper bound
Every domino covers exactly 2 squares, and there are M × N squares. So you can never place more than ⌊MN / 2⌋ dominoes.
That bound is always reachable
We only need one way to reach it:
- If N is even, fill every row with N/2 horizontal dominoes. Every square is covered, and we used MN/2 dominoes.
- If N is odd, fill each row with (N − 1)/2 horizontal dominoes, leaving the last column empty. That column has M squares, so place ⌊M/2⌋ vertical dominoes in it. At most one square on the whole board is left uncovered, which is exactly what ⌊MN/2⌋ allows.
So the answer is simply (M × N) / 2 using integer division.
Examples
- 2 × 4 board: 8 squares, so 4 dominoes, two horizontal ones per row.
- 3 × 3 board: 9 squares, so 4 dominoes. One square always stays empty because 9 is odd.
Solution in C
#include <stdio.h>
int main(void) {
int m, n;
scanf("%d %d", &m, &n);
/* Every domino covers 2 squares, and a board can always be tiled
leaving at most one square empty. */
printf("%d\n", (m * n) / 2);
return 0;
}
With M, N ≤ 16 the product is at most 256, so int is more than enough.
Complexity
O(1) time and memory.
What to take away
A pattern that shows up again and again in competitive programming: find a simple upper bound (here, area divided by 2), then show a construction that reaches it. When both match, you have the answer without any search. Compare this with 1A Theatre Square, where stones may overhang, so the answer rounds up instead of down.