문제 >
크기가 N×N인 도시가 있다. 도시는 1×1크기의 칸으로 나누어져 있다. 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸, 왼쪽에서부터 c번째 칸을 의미한다. r과 c는 1부터 시작한다.
이 도시에 사는 사람들은 치킨을 매우 좋아한다. 따라서, 사람들은 "치킨 거리"라는 말을 주로 사용한다. 치킨 거리는 집과 가장 가까운 치킨집 사이의 거리이다. 즉, 치킨 거리는 집을 기준으로 정해지며, 각각의 집은 치킨 거리를 가지고 있다. 도시의 치킨 거리는 모든 집의 치킨 거리의 합이다.
임의의 두 칸 (r1, c1)과 (r2, c2) 사이의 거리는 |r1-r2| + |c1-c2|로 구한다.
예를 들어, 아래와 같은 지도를 갖는 도시를 살펴보자.
0 2 0 1 0
1 0 1 0 0
0 0 0 0 0
0 0 0 1 1
0 0 0 1 2
0은 빈 칸, 1은 집, 2는 치킨집이다.
(2, 1)에 있는 집과 (1, 2)에 있는 치킨집과의 거리는 |2-1| + |1-2| = 2, (5, 5)에 있는 치킨집과의 거리는 |2-5| + |1-5| = 7이다. 따라서, (2, 1)에 있는 집의 치킨 거리는 2이다.
(5, 4)에 있는 집과 (1, 2)에 있는 치킨집과의 거리는 |5-1| + |4-2| = 6, (5, 5)에 있는 치킨집과의 거리는 |5-5| + |4-5| = 1이다. 따라서, (5, 4)에 있는 집의 치킨 거리는 1이다.
이 도시에 있는 치킨집은 모두 같은 프랜차이즈이다. 프렌차이즈 본사에서는 수익을 증가시키기 위해 일부 치킨집을 폐업시키려고 한다. 오랜 연구 끝에 이 도시에서 가장 수익을 많이 낼 수 있는 치킨집의 개수는 최대 M개라는 사실을 알아내었다.
도시에 있는 치킨집 중에서 최대 M개를 고르고, 나머지 치킨집은 모두 폐업시켜야 한다. 어떻게 고르면, 도시의 치킨 거리가 가장 작게 될지 구하는 프로그램을 작성하시오.
입력 >
첫째 줄에 N(2 ≤ N ≤ 50)과 M(1 ≤ M ≤ 13)이 주어진다.
둘째 줄부터 N개의 줄에는 도시의 정보가 주어진다.
도시의 정보는 0, 1, 2로 이루어져 있고, 0은 빈 칸, 1은 집, 2는 치킨집을 의미한다. 집의 개수는 2N개를 넘지 않으며, 적어도 1개는 존재한다. 치킨집의 개수는 M보다 크거나 같고, 13보다 작거나 같다.
출력 >
첫째 줄에 폐업시키지 않을 치킨집을 최대 M개를 골랐을 때, 도시의 치킨 거리의 최솟값을 출력한다.
해결방법 >
그리디로 해결하려다가 최적값을 구하는 조건을 못찾았고 결국 완전탐색을 했다.
문제를 해결하기 위해 아래와 같은 과정을 거쳤다.
1) DFS(깊이우선탐색) m개의 치킨집을 선택하는 모든 경우를 찾는다.
2) 1)을 통해 m개의 치킨집을 선택했다면 각 집마다 치킨 거리를 구하고 총합을 구한다.
3) 각 경우의 총합 중 최솟값을 찾는다.
첫번째 코드는 2)번 과정에서 BFS로 치킨 거리를 구했더니
실행 시간이 다른 사람이 제출한 코드보다 5배가 넘었고 메모리 사용량을 말도 못한다;;;;;
잘생각해보니까 2)번 과정을 굳이 BFS로 할 필요없이 집마다 선택된 m개의 치킨집이랑 비교해가면서 치킨 거리를 찾으면 되는거였다.
수정한 코드는 두번째 코드이다. 왜 매번 굳이굳이 돌아서가는걸까...하...........ㅠㅠ
[JAVA]
package baekjoon;
import java.util.*;
import java.io.*;
public class BOJ_15686 {
static int cnt;
static int m;
static int n;
static int[][] a;
static ArrayList<Node> point;
static int min;
public static class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
public static void select(int idx, int flag, int[] s, int depth) {
if(idx >= cnt) return;
int[] store = new int[cnt];
for(int i = 0; i < cnt; i++) {
store[i] = s[i];
}
store[idx] = flag;
if(depth == m) {
cal(store);
return;
}
select(idx+1, 0, store, depth);
select(idx+1, 1, store, depth+1);
}
public static void cal(int[] s) {
int[][] map = new int[n][n];
Queue <Node> q = new LinkedList<>();
int[][] visit = new int[n][n];
int[] dx = {-1, 0, 1, 0};
int[] dy = {0 ,1, 0, -1};
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
map[i][j] = a[i][j];
}
}
for(int i = 0; i < cnt; i++) {
if(s[i] == 0) {
map[point.get(i).x][point.get(i).y] = 0;
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(map[i][j] == 2) {
visit[i][j] = 1;
q.add(new Node(i, j));
}
}
}
int d = 0;
while(!q.isEmpty()) {
Node node = q.poll();
int x = node.x;
int y = node.y;
for(int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if(nx >= 0 && ny >= 0 && nx < n && ny < n && visit[nx][ny] == 0) {
if(a[nx][ny] == 1) {
d += visit[x][y];
}
visit[nx][ny] = visit[x][y] + 1;
q.add(new Node(nx, ny));
}
}
}
min = Math.min(d, min);
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(br.readLine());
n = Integer.parseInt(tk.nextToken());
m = Integer.parseInt(tk.nextToken());
a = new int[n][n];
point = new ArrayList<>();
cnt = 0;
min = 99999999;
for(int i = 0; i < n; i++) {
tk = new StringTokenizer(br.readLine());
for(int j = 0; j < n; j++) {
a[i][j] = Integer.parseInt(tk.nextToken());
if(a[i][j] == 2) {
cnt++;
point.add(new Node(i, j));
}
}
}
int[] store = new int[cnt];
select(0, 0, store, 0);
select(0, 1, store, 1);
System.out.println(min);
}
}
package baekjoon;
import java.util.*;
import java.io.*;
public class BOJ_15686_2 {
static ArrayList <Node> people;
static ArrayList <Node> store;
static int n;
static int m;
static int cnt;
static int min;
public static class Node{
int x;
int y;
Node(int x, int y){
this.x = x;
this.y = y;
}
}
public static void dfs(int idx, int flag, int depth, int[] s) {
if(idx == cnt) return;
int[] b = new int[cnt];
for(int i = 0; i < cnt; i++) {
b[i] = s[i];
}
b[idx] = flag;
if(depth == m) {
int total = 0;
for(int i = 0; i < people.size(); i++) {
int shortest = 9999999;
for(int j = 0; j < cnt; j++) {
if(b[j] == 1) {
int d = Math.abs(people.get(i).x - store.get(j).x) + Math.abs(people.get(i).y - store.get(j).y);
shortest = Math.min(d, shortest);
}
}
total += shortest;
}
min = Math.min(total, min);
return;
}
dfs(idx+1, 0, depth, b);
dfs(idx+1, 1, depth+1, b);
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer tk = new StringTokenizer(br.readLine());
n = Integer.parseInt(tk.nextToken());
m = Integer.parseInt(tk.nextToken());
cnt = 0;
min = 99999999;
people = new ArrayList<>();
store = new ArrayList<>();
for(int i = 0; i < n; i++) {
tk = new StringTokenizer(br.readLine());
for(int j = 0; j < n; j++) {
int tmp = Integer.parseInt(tk.nextToken());
if(tmp == 1) {
people.add(new Node(i, j));
}
else if(tmp == 2) {
store.add(new Node(i, j));
cnt++;
}
}
}
int[] a = new int[cnt];
dfs(0, 0, 0, a);
dfs(0, 1, 1, a);
System.out.println(min);
}
}
'Problem Solving > BOJ' 카테고리의 다른 글
[백준] 17837번 - 새로운 게임 2 (0) | 2020.03.16 |
---|---|
[백준] 17140번 - 이차원 배열과 연산 (0) | 2020.03.15 |
[백준] 17779번 - 게리맨더링 2 (0) | 2020.03.14 |
[백준] 14891번 - 톱니바퀴 (0) | 2020.03.14 |
[백준] 14888번 - 연산자 끼워넣기 (0) | 2020.03.14 |
댓글