Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Archives
Today
Total
관리 메뉴

Life Engineering

[BOJ 15686] 치킨 배달 (Python3) 본문

Problem Solving

[BOJ 15686] 치킨 배달 (Python3)

흑개 2021. 2. 15. 20:32

www.acmicpc.net/problem/15686

 

15686번: 치킨 배달

크기가 N×N인 도시가 있다. 도시는 1×1크기의 칸으로 나누어져 있다. 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸

www.acmicpc.net

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
from itertools import combinations
 
N, M=map(int, input().split())
graph=[]
houses=[]
chickens=[]
result2=int(1e9)
result1=int(1e9)
 
for i in range(N):
    graph.append(list(map(int, input().split())))
    for j in range(N):
        if graph[i][j]==1:
            houses.append((i,j))
        elif graph[i][j]==2:
            chickens.append((i,j))
 
for i in range(1,M+1):
    l=list(combinations(chickens,i))
    for c in l:
        totaldist=0
        for hx,hy in houses:
            mini=int(1e9)
            for cx, cy in c:
                mini=min(abs(hx-cx)+abs(hy-cy),mini)
            totaldist+=mini
        result2=min(result2, totaldist)
    result1=min(result1, result2)
 
print(result1)
cs

 

 

구현+Brute Force 문제

치킨집이 m개일 때 모든 조합 수를 구한 뒤, 조합 수에 따라 각 집에 따른 치킨 거리를 구한 뒤 총 치킨 거리가 최소값인 아이를 리턴한다.

내가 보는 책인 "이것이 코딩 테스트다"에 이 문제에 대한 답 코드가 있었는데, 비슷하게 해결했다!!(HOOLAY!)

다만..

나처럼 치킨집이 1개, 2개, ..., m개일때를 모두 고려하여 조합수를 구해 최소값을 구한 게 아니라

m개일 때만 고려하였다는 점이다.

참.. 당연한 것이다. 치킨 집이 많을 수록 치킨 거리는 짧아지는 법이니!
m개만 고려해도 되는 것이다.

그리고 총 치킨 거리를 구하는 부분을 함수로 따로 빼는게 가독성에 좋을 것 같다.

 

 

++백트래킹으로도 풀 수 있다.

근데 코드를 봤는데..이해를 못하겠다!! 케이스를 나눠서(??) 재귀로 푸는건 알겠는디.. 재귀 복잡해서.. 이해하기가 어렵다.. 흑..일단은 보류

steady-coding.tistory.com/23참조.

import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.InputStreamReader;

import java.io.OutputStreamWriter;

import java.util.ArrayList;

import java.util.StringTokenizer;

 

class Point {

    int x;

    int y;

 

    Point(int x, int y) {

        this.x = x;

        this.y = y;

    }

}

 

public class Main {

    static int N, M;

    static int[][] map;

    static ArrayList<Point> person;

    static ArrayList<Point> chicken;

    static int ans;

    static boolean[] open;

 

    public static void main(String[] args) throws Exception {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        StringTokenizer st = new StringTokenizer(br.readLine());

 

        N = Integer.parseInt(st.nextToken());

        M = Integer.parseInt(st.nextToken());

 

        map = new int[N][N];

        person = new ArrayList<>();

        chicken = new ArrayList<>();

 

        // 미리 집과 치킨집에 해당하는 좌표를 ArrayList에 넣어 둠.

        for (int i = 0; i < N; i++) {

            st = new StringTokenizer(br.readLine());

            for (int j = 0; j < N; j++) {

                map[i][j] = Integer.parseInt(st.nextToken());

 

                if (map[i][j] == 1) {

                    person.add(new Point(i, j));

                } else if (map[i][j] == 2) {

                    chicken.add(new Point(i, j));

                }

            }

        }

 

        ans = Integer.MAX_VALUE;

        open = new boolean[chicken.size()];

 

        DFS(0, 0);

        bw.write(ans + "\n");

        bw.flush();

        bw.close();

        br.close();

    }

 

    public static void DFS(int start, int cnt) {

        if (cnt == M) {

            int res = 0;

 

            for (int i = 0; i < person.size(); i++) {

                int temp = Integer.MAX_VALUE;

 

                // 어떤 집과 치킨집 중 open한 치킨집의 모든 거리를 비교한다.

                // 그 중, 최소 거리를 구한다.

                for (int j = 0; j < chicken.size(); j++) {

                    if (open[j]) {

                        int distance = Math.abs(person.get(i).x - chicken.get(j).x)

                                + Math.abs(person.get(i).y - chicken.get(j).y);

 

                        temp = Math.min(temp, distance);

                    }

                }

                res += temp;

            }

            ans = Math.min(ans, res);

            return;

        }

 

        // 백트래킹

        for (int i = start; i < chicken.size(); i++) {

            open[i] = true;

            DFS(i + 1, cnt + 1);

            open[i] = false;

        }

    }

 

}