Chicken Delivery
InterviewTime limit1sMemory limit512 MB
Choose at most M of the chicken restaurants to keep open so that the sum over all houses of the distance to the nearest open restaurant is minimized.
- Level
Medium7 of 10
- Topics
- Brute force, Backtracking, Combinatorics, Implementation
- Solved
- No attempts yet
Problem
A city is an grid. It is divided into cells of size , and each cell is an empty cell, a chicken restaurant, or a house. A cell is written as , which means the -th row from the top and the -th column from the left. Both and start at 1.
The people who live in this city like chicken very much, so they often talk about the chicken distance. The chicken distance is the distance between a house and the chicken restaurant closest to it. It is defined with respect to a house, so each house has one chicken distance. The chicken distance of the city is the sum of the chicken distances of all houses.
The distance between two cells and is .
For example, look at the city with the map below.
0 2 0 1 0
1 0 1 0 0
0 0 0 0 0
0 0 0 1 1
0 0 0 1 2
0 is an empty cell, 1 is a house, and 2 is a chicken restaurant.
The distance from the house at to the chicken restaurant at is , and the distance to the chicken restaurant at is . The chicken distance of that house is 2.
The distance from the house at to the chicken restaurant at is , and the distance to the chicken restaurant at is . The chicken distance of that house is 1.
Every chicken restaurant in this city belongs to the same franchise. The head office wants to close some of them to raise profit. After a long study it found that the number of chicken restaurants that earns the most profit in this city is at most .
You must choose at most of the chicken restaurants in the city and close all the rest. Write a program that finds how small the chicken distance of the city can become.
Input
The first line contains () and ().
Each of the next lines describes one row of the city. A line contains numbers separated by spaces, where 0 is an empty cell, 1 is a house, and 2 is a chicken restaurant. The number of houses does not exceed , and there is at least 1 house. The number of chicken restaurants is at least and at most 13.
Output
Print on the first line the minimum chicken distance of the city when at most chicken restaurants are kept open.