반응형
문제 출처 :
https://www.acmicpc.net/problem/15686
알고리즘 분석 :
문제 해결에 필요한 사항
1. 백트래킹
백트래킹으로 문제를 해결 할 수 있다.
각 치킨집을 nCr로 고르면서 치킨집을 모두 다 골랐을 때 거리의 최솟값을 갱신해주면 된다.
이때 return되는 값이 최솟값이 된다.
이 문제를 풀기 전 아래 링크문제부터 풀어보자.
http://www.crocus.co.kr/1240?category=209527
소스 코드 :
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 65 66 67 68 69 70 71 72 73 | #include <iostream> #include <cstdio> #include <vector> #include <algorithm> using namespace std; typedef pair<int, int> pii; vector<pii> chicken; vector<pii> house; int n, m; int dfs(vector<pii> vc, int pos) { int ret = 98754321; if (vc.size() == m) { int sum = 0; for (int i = 0; i < house.size(); i++) { int hy = house[i].first; int hx = house[i].second; int minVal = 987654321; for (int j = 0; j < vc.size(); j++) { int cy = vc[j].first; int cx = vc[j].second; minVal = min(minVal, abs(cy - hy) + abs(cx - hx)); } sum += minVal; } return min(ret, sum); } for (int i = pos; i < chicken.size(); i++) { vc.push_back(chicken[i]); ret = min(ret, dfs(vc, i + 1)); vc.pop_back(); } return ret; } int main() { scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) { for(int j = 0 ; j < n ; j ++) { int val; scanf("%d", &val); if (val == 1) house.push_back({ i,j }); else if (val == 2) chicken.push_back({ i,j }); } } vector<pii> vc; printf("%d\n",dfs(vc, 0)); return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Applied > 알고리즘 문제풀이' 카테고리의 다른 글
[13275번] 가장 긴 팰린드롬 부분 문자열 (2) | 2018.05.03 |
---|---|
[11008번] 복붙의 달인 (0) | 2018.05.01 |
[15685번] 드래곤 커브 (0) | 2018.04.28 |
[11663번] 선분 위의 점 (0) | 2018.04.19 |
[2567번] 색종이1 (0) | 2018.04.16 |