The city has H homes and C chicken stores. Choose exactly M stores to remain open. A home’s chicken distance is its Manhattan distance to the nearest open store, and the city’s chicken distance is the sum of those nearest-store distances over all homes. The goal is to minimize this total.
Enumerate combinations rather than permutations: the DFS chooses store indices in increasing order. start is the first index allowed for the next choice, and selected contains the current partial combination. Once it contains M stores, compute the city’s distance by scanning each home and taking its minimum distance to a selected store. Then update the global minimum.
Before branching, let remaining = C - start be the number of stores still available and needed = M - selected.size() the number still required. If remaining < needed, this branch cannot be completed and is pruned. This condition is false when exactly enough candidates remain, so that boundary branch is still explored. At M = 1, each single store is evaluated; at M = C, the only complete combination is evaluated.
There are C choose M complete combinations, and evaluating one takes O(H*M), for O((C choose M) * H*M) time. The home and store lists and the current selection use O(H+C) space. Distances and the accumulated city total use long long.
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <algorithm>
#include <iostream>
#include <limits>
#include <vector>
using namespace std;
struct Point {
int row;
int col;
};
int m;
vector<Point> homes;
vector<Point> stores;
vector<int> selected;
long long answer = numeric_limits<long long>::max();
int manhattan(const Point &a, const Point &b) {
return abs(a.row - b.row) + abs(a.col - b.col);
}
void search(int start) {
if (static_cast<int>(selected.size()) == m) {
long long total = 0;
for (const Point &home : homes) {
int nearest = numeric_limits<int>::max();
for (int index : selected) {
nearest = min(nearest, manhattan(home, stores[index]));
}
total += nearest;
}
answer = min(answer, total);
return;
}
const int needed = m - static_cast<int>(selected.size());
const int remaining = static_cast<int>(stores.size()) - start;
if (remaining < needed) return;
for (int i = start; i <= static_cast<int>(stores.size()) - needed; ++i) {
selected.push_back(i);
search(i + 1);
selected.pop_back();
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n >> m;
for (int row = 0; row < n; ++row) {
for (int col = 0; col < n; ++col) {
int cell;
cin >> cell;
if (cell == 1) homes.push_back({row, col});
else if (cell == 2) stores.push_back({row, col});
}
}
search(0);
cout << answer << '\n';
}