|
| 1 | +#include <bits/stdc++.h> |
| 2 | +#define MAX 2147483647 |
| 3 | + |
| 4 | +using namespace std; |
| 5 | + |
| 6 | +vector<pair<int, int>> chickens, houses; |
| 7 | +vector<int> current; |
| 8 | +int m; |
| 9 | +int res = MAX; |
| 10 | + |
| 11 | +void rec(int x) |
| 12 | +{ |
| 13 | + int size = current.size(); |
| 14 | + if (size == m) |
| 15 | + { |
| 16 | + int dis = 0; |
| 17 | + int houses_len = houses.size(); |
| 18 | + int crt_len = current.size(); |
| 19 | + for (int i = 0; i < houses_len; i++) |
| 20 | + { |
| 21 | + int d = MAX; |
| 22 | + for (int j = 0; j < crt_len; j++) |
| 23 | + { |
| 24 | + d = min(d, abs(houses[i].first - chickens[current[j]].first) + abs(houses[i].second - chickens[current[j]].second)); |
| 25 | + } |
| 26 | + dis += d; |
| 27 | + } |
| 28 | + res = min(res, dis); |
| 29 | + } |
| 30 | + else if (size < m) |
| 31 | + { |
| 32 | + int len = chickens.size(); |
| 33 | + for (int i = x + 1; i < len; i++) |
| 34 | + { |
| 35 | + current.push_back(i); |
| 36 | + rec(i); |
| 37 | + current.pop_back(); |
| 38 | + } |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +int main() |
| 43 | +{ |
| 44 | + int n, i, j, d; |
| 45 | + cin >> n >> m; |
| 46 | + for (i = 0; i < n; i++) |
| 47 | + { |
| 48 | + for (j = 0; j < n; j++) |
| 49 | + { |
| 50 | + cin >> d; |
| 51 | + if (d == 2) |
| 52 | + { |
| 53 | + chickens.push_back(make_pair(i, j)); |
| 54 | + } |
| 55 | + else if (d == 1) |
| 56 | + { |
| 57 | + houses.push_back(make_pair(i, j)); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + rec(-1); |
| 62 | + cout << res; |
| 63 | + return 0; |
| 64 | +} |
0 commit comments