Noisy Neighbors
InterviewTime limit5sMemory limit512 MB
Place N tenants on an R by C grid to minimize the number of shared walls between occupied neighbors.
- Level
Medium4 of 10
- Topics
- Brute force, Bit manipulation
- Solved
- No attempts yet
Problem
You are a landlord. Your building is an grid of apartments, and each apartment is a unit square with four walls. You want to rent out of the apartments to tenants, exactly one tenant per apartment, and leave the rest empty.
Every tenant is noisy. Whenever two occupied apartments share a wall, the building gains one point of unhappiness. Two apartments that touch only at a corner do not share a wall. For example, a building with all four apartments occupied has four walls between neighboring tenants, so its unhappiness is 4.
Place the tenants so that the unhappiness is as small as possible, and report that minimum.
Input
The first line contains the number of test cases . Each of the next lines contains three integers , , and , separated by single spaces.
Limits
Output
For each test case, print one line of the form Case #x: y, where is the test case number starting at 1 and is the minimum possible unhappiness of the building.
Notes
In sample case 1, every apartment of the building is occupied, so all seven internal walls sit between two tenants.
In sample case 2, the two tenants fit into the building in several ways without sharing a wall.
In sample case 3, the best placement puts the eight tenants in a ring along the border of the building and leaves the middle apartment empty.
The picture below shows sample cases 1, 2, and 3. Each red wall costs one point of unhappiness.
