Symmetry
Time limit1sMemory limit128 MB
Count the squares a recursive center-splitting process marks on an N by M grid, where each step splits an odd-by-odd field into four half-sized subfields.
- Level
Medium5 of 10
- Topics
- Recursion, Math, Divide and conquer, Implementation
- Solved
- No attempts yet
Problem
Farmer John loves symmetry and is arranging his cows on a field partitioned into an grid (, ).
To preserve symmetry, he places cows as follows. He puts one cow on the exact center square of the field; if the field has no center square, he stops. He then splits the field into four equally sized subfields, separated by the row and column of the center cow, and arranges cows on each subfield in the same way. He repeats this on ever-smaller subfields until a subfield has no center square or can no longer be divided.
A field has a center square only when both of its side lengths are odd. Splitting an field (with and both odd) produces four subfields of size .
For example, if and , Farmer John places a cow at row 4, column 8, then processes each resulting subfield; in each subfield he places a cow at row 2, column 4 and processes each resulting subfield. The process is shown below (C denotes a cow):
............... ............... .......|....... .C.|.C.|.C.|.C.
............... ............... ...C...|...C... ---C---|---C---
............... ............... .......|....... .C.|.C.|.C.|.C.
............... -> .......C....... -> -------C------- -> -------C-------
............... ............... .......|....... .C.|.C.|.C.|.C.
............... ............... ...C...|...C... ---C---|---C---
............... ............... .......|....... .C.|.C.|.C.|.C.
This field needs 21 cows. In contrast, if , only one cow is needed, because the resulting subfields have no center square. Help Farmer John determine how many cows he needs.
Input
A single line with two space-separated integers and .
Output
The number of cows needed, on a single line.