https://www.acmicpc.net/problem/15686
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<pair<int, int>> houses;
vector<pair<int, int>> stores;
int getdistance(pair<int, int> x, pair<int, int> y) {
int ret = 0;
if (x.first >= y.first) ret += x.first - y.first;
else ret += y.first - x.first;
if (x.second >= y.second) ret += x.second - y.second;
else ret += y.second - x.second;
return ret;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int tem = 0;
cin >> tem;
if (tem == 2) stores.push_back(make_pair(i, j));
else if (tem == 1) houses.push_back(make_pair(i, j));
}
}
vector<int> choice;
for (int i = 0; i < stores.size() - m; i++) {
choice.push_back(0);
}
for (int i = 0; i < m; i++) {
choice.push_back(1);
}
int ret = -1;
do{
int tem = 0;
for (int j = 0; j < houses.size(); j++) {
int minval = -1;
for (int i = 0; i < choice.size(); i++) {
if (choice[i] == 1) {
if (minval != -1) minval = min(minval, getdistance(houses[j], stores[i]));
else minval = getdistance(houses[j], stores[i]);
}
}
tem += minval;
}
if (ret != -1) ret = min(ret, tem);
else ret = tem;
} while (next_permutation(choice.begin(),choice.end()));
cout << ret << "\n";
return 0;
}
직접 DFS로 조합을 구하여 풀었다
https://jaimemin.tistory.com/1059