21.07.31 기록

최대 1 분 소요

  • 백준 알고리즘 1085 풀이

    • 나의 풀이(메모리 14.2MB, 시간 136ms로 통과)
      좌표를 그려보면, x, y, (w-x), (h-y)중 최솟값을 출력하면 되는 것을 알 수 있다.
      최솟값 변수 min을 (w-x)값으로 초기화한 후, if문을 통해 나머지값을 비교했다.
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.StringTokenizer;
    
    public class B1085 {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            StringTokenizer st = new StringTokenizer(br.readLine(), " ");
    
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());
            int w = Integer.parseInt(st.nextToken());
            int h = Integer.parseInt(st.nextToken());
    
            int min = (w-x);
    
            if(x < min) { min = x; }
            if((h-y) < min) { min = (h-y); }
            if(y < min) { min = y; }
    
            System.out.println(min);
        }
    }
    


    • 해설 (메모리 14.2MB, 시간 132ms로 통과)
      Math.min() 함수를 사용한 풀이다.
      Math.min(x,y) - x,y 값을 비교한 후 더 작은 값을 반환한다.
     import java.io.BufferedReader;
     import java.io.IOException;
     import java.io.InputStreamReader;
     import java.util.StringTokenizer;
    
     public class B1085 {
         public static void main(String[] args) throws IOException {
             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
             StringTokenizer st = new StringTokenizer(br.readLine(), " ");
    
             int x = Integer.parseInt(st.nextToken());
             int y = Integer.parseInt(st.nextToken());
             int w = Integer.parseInt(st.nextToken());
             int h = Integer.parseInt(st.nextToken());
    
             int xMin = Math.min(x, w-x); //x축 최소거리
             int yMin = Math.min(y, h-y); //y축 최소거리
    
             System.out.println( Math.min(xMin, yMin) ); //최솟값 출력
         }
     }
    

카테고리:

업데이트: