-
백준 16945번 매직 스퀘어로 변경하기PS 2020. 3. 17. 19:41
https://www.acmicpc.net/problem/16945
16945번: 매직 스퀘어로 변경하기
1부터 N2까지의 수가 하나씩 채워져 있는 크기가 N×N인 배열이 있고, 이 배열의 모든 행, 열, 길이가 N인 대각선의 합이 모두 같을 때, 매직 스퀘어라고 한다. 크기가 3×3인 배열 A가 주어졌을 때, 이 배열을 매직 스퀘어로 변경하려고 한다. 한 칸에 있는 수 a를 b로 변경하는 비용은 |a - b| 이다. 예를 들어, 아래와 같은 경우를 살펴보자. 5 3 4 1 5 8 6 4 2 이 배열의 수를 아래와 같이 변경하면 매직 스퀘어가 되고, 비용은
www.acmicpc.net
<접근방법>
n이 매우 작으므로 완전 탐색으로 풀 수 있습니다.
순열로 사각형을 만들어서 가중치를 계산하고 최솟값을 저장해나갑니다.
<느낀 점>
<코드>
#include <iostream> #include <algorithm> using namespace std; int a[9], b[9], res = 98765431; bool visit[10]; int cal() { int tres = 0; for (int i = 0; i < 9; i++) { int tmp = abs(a[i] - b[i]); tres += tmp; } return tres; } bool check() { int sum = b[0] + b[1] + b[2]; for (int i = 0; i < 3; i++) { int tsum = 0; for (int j = 0; j < 3; j++) { tsum += b[i * 3 + j]; } if (sum != tsum) return false; } for (int i = 0; i < 3; i++) { int tsum = 0; for (int j = 0; j < 9; j += 3) { tsum += b[i + j]; } if (sum != tsum) return false; } int tsum = b[0] + b[4] + b[8]; if (sum != tsum) return false; tsum = b[2] + b[4] + b[6]; if (sum != tsum) return false; return true; } void dfs(int dep = 0) { if (dep == 9) { if (check()) { res = min(res, cal()); } return; } for (int i = 1; i <= 9; i++) { if (visit[i]) continue; visit[i] = true; b[dep] = i; dfs(dep + 1); visit[i] = false; } } int main() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { cin >> a[i*3 + j]; } } dfs(); cout << res << '\n'; return 0; }
반응형'PS' 카테고리의 다른 글
백준 17085번 십자가 2개 놓기 (1) 2020.03.18 백준 16943번 숫자 재배치 (0) 2020.03.17 백준 16951번 블록 놀이 (0) 2020.03.17 백준 16937번 두 스티커 (0) 2020.03.15 백준 16638번 괄호 추가하기2 (0) 2020.03.15