21.07.01 기록

1 분 소요

  • 백준 알고리즘 2839 풀이

    • 나의 풀이(메모리 14.3MB, 시간 124ms로 통과)
      최대한 적은 봉지 수를 구해야 하기 때문에, 5로 나눈 몫과 나머지 값을 기준으로 경우의 수를 생각했다.
      (1)N이 5의 배수일 때
      (2)N이 5와 3으로 나눠질 때
      (3)N이 3의 배수일 때
      (4)N이 3 또는 5로 표현할 수 없을 때
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class B2839 {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int N = Integer.parseInt(br.readLine());
    
            int share = N/5;
            //1. 5의 배수인 경우
            if(N%5 == 0) {
                System.out.println(share);
                return;
            }
    
            //2. (N % 5) 값이 3으로 나눠지는 경우
            if(share > 0) {
                for(int i = share; i >= 1; i--) {
                    int remainder = N - (5 * i);
    
                    if( (remainder % 3) == 0 ) {
                        System.out.println(i + (remainder/3));
                        return;
                    }
                }
            }
    
            //3. N이 3의 배수인 경우
            if( (N % 3) == 0 ) {System.out.println(N/3);}
            //4. N이 정확히 떨어지지 않는 경우
            else { System.out.println(-1); }
        }
    }
    
    


    • 해설(메모리 14.2MB, 시간 128ms로 통과)
      수학적인 규칙을 찾고 4개의 if-else if 구문으로 풀이하셨다.
      ★골드바흐의 추측에 의해 4와 7만이 3과 5로 구성될 수 없다.
    import java.io.InputStreamReader;
    import java.io.BufferedReader;
    import java.io.IOException;
    
    public class B2839 {
        public static void main(String[] args) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            int N = Integer.parseInt(br.readLine());
    
            int share = N/5;
            int remainder = N%5;
    
            if (N == 4 || N == 7) {
                System.out.println(-1);
            }
            else if (remainder == 0) {
                System.out.println(share);
            }
            else if (remainder == 1 || remainder == 3) {
                System.out.println(share + 1);
            }
            else if (remainder == 2 || remainder == 4) {
                System.out.println(share + 2);
            }
        }
    }
    
    


카테고리:

업데이트: