티스토리 뷰
직사각형 테두리에 북남서동 (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");
}
}
}
'알고리즘 기록' 카테고리의 다른 글
(Java) SWEA 5432 쇠막대기 자르기 - stack (0) | 2024.08.05 |
---|---|
(Java) SWEA 1244 최대 상금 (0) | 2024.08.04 |
(Java) Baekjoon 10157 자리배정 vs SWEA 1954 달팽이 (0) | 2024.08.03 |
(Java) Baekjoon 10158 개미 (실버3) (0) | 2024.07.30 |
(Java) n번째까지 출력 후 줄 넘기기, 양 끝 피라미드 별 (0) | 2024.07.26 |