[Link] https://www.acmicpc.net/problem/15686
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
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
typedef long long ll;
const int INF = 987654321;
int n, m, ans = INF;
struct point{ int i, j; };
vector<point> chicken;
vector<point> home;
vector<point> select_chicken;
int distance(point p1, point p2) { return abs(p1.i - p2.i) + abs(p1.j - p2.j); }
void dfs(int startIdx, int cnt) {
if(cnt == m) {
int mintmp = 0;
for(point hp: home) {
int dis = INF;
for(point cp : select_chicken) dis = min(dis, distance(hp, cp));
mintmp += dis;
}
ans = min(ans, mintmp);
return;
}
if(cnt < m - ((int)chicken.size() - startIdx)) return;
for(int i = startIdx; i < chicken.size(); i++) {
select_chicken.push_back(chicken[i]);
dfs(i + 1, cnt + 1);
select_chicken.pop_back();
}
}
int main() {
cin >> n >> m;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int in;
cin >> in;
if(in == 0) continue;
point p;
p.i = i, p.j = j;
if(in == 1) home.push_back(p);
else chicken.push_back(p);
}
}
dfs(0, 0);
cout << ans;
return 0;
}