[백준] 2839번 설탕 배달 (JAVA)

sarah·2023년 1월 19일
0

BaekJoon

목록 보기
4/11

  • 총 무게 : weight
  • 3kg 개수 : x
  • 5kg 개수 : y

주의할 점

두 개의 개수를 구해야 하기 때문에 일단 이중 for문을 돌린다.
문제에서 봉지의 최소 개수를 출력한다 라는 문구를 통해, 이중 for문의 안쪽 for문은 5kg의 개수인 y가 기준이 된다. 그러면 x는 최소, y는 최대인 case를 먼저 찾을 수 있다.

코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int weight = Integer.parseInt(br.readLine());

        int x = weight/3;
        int y = weight/5;

        int cnt = -1;
        for(int i=0; i<=x; i++) {
            for(int j=0; j<=y; j++) {
                if( 3*i + 5*j == weight ) {
                    cnt = i + j;
                    break;
                }
            }
            if( cnt != -1 ) {
                break;
            }
        }
        System.out.println(cnt);
    }
}

0개의 댓글