티스토리 뷰

직사각형 테두리에 북남서동 (1234)와 거리를 받아서 

가게와 경비원의 최소 거리 합을 구하는 문제 

 

-> 1 - 4 - 2 - 3으로 1차원 거리를 만들어서 위치에 놓아주고 

차 vs (전체합 - 차)를 비교해서 작은 값을 선택 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // 직사각형의 너비와 높이 입력
        int width = scanner.nextInt();
        int height = scanner.nextInt();
        int n = scanner.nextInt(); // 상점의 개수
        
        int totalPerimeter = (width + height) * 2;
        int[] shopDistances = new int[n + 1]; // 상점과 경비원의 위치 저장
        
        for (int i = 0; i <= n; i++) {
            int direction = scanner.nextInt();
            int distance = scanner.nextInt();
            shopDistances[i] = convertTo1DPosition(direction, distance, width, height);
        }
        
        int totalDistance = 0;
        for (int i = 0; i < n; i++) {
            int distance = Math.abs(shopDistances[i] - shopDistances[n]);
            totalDistance += Math.min(distance, totalPerimeter - distance);
        }
        
        System.out.println(totalDistance);
    }

    // 방향과 거리를 1차원 좌표계로 변환하는 메서드
    private static int convertTo1DPosition(int direction, int distance, int width, int height) {
        switch (direction) {
            case 1: // 북쪽
                return distance;
            case 2: // 남쪽
                return width + height + (width - distance);
            case 3: // 서쪽
                return width * 2 + height + (height - distance);
            case 4: // 동쪽
                return width + distance;
            default:
                throw new IllegalArgumentException("Invalid direction");
        }
    }
}
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/07   »
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
글 보관함