[백준] 2839번 설탕 배달 / C++ Java

SmileJun·2025년 3월 6일

알고리즘

목록 보기
15/34

문제 : https://www.acmicpc.net/problem/2839

C++

#include<iostream>
using namespace std;

// N에서 3을 빼면서, 5의 배수가 되면 나눈다.
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n;
    cin >> n;
    int total = 0;
    while(true) {
        if(n % 5 == 0) {
            total += n / 5;
            break;
        }
        else if(n < 0) {
            total = -1;
            break;
        }
        n-=3;
        total++;
    }
    cout<< total << endl;
}

Java


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));

        int n = Integer.parseInt(br.readLine());
        int total = 0;
        while(true) {
            if(n % 5 == 0) {
                total += n / 5;
                break;
            }
            else if(n < 0) {
                total = -1;
                break;
            }
            n-=3;
            total++;
        }
        bw.write(total + "\n");
        bw.flush();
        bw.close();
        br.close();
    }
}

문제풀이

  • 더 적은 개수의 봉지로 배달하려면, 5킬로그램 봉지를 최대한 많이 사용해야한다. 따라서 n의 값을 계속 3으로 빼주면서, n % 5 == 0가 되면 그 값만큼 더하고, 반복문을 끝낸다. 그리고 정확하게 n킬로그램을 만들 수 없을 때는 -1을 출력해야되기 때문에 n < 0일 때 -1 출력한다.

Comment

  • 5킬로그램 봉지가 최대한 많이 사용된다. 이걸 중심으로 알고리즘을 짜면 큰 어려움이 없다.
profile
하루하루는 성실하게, 인생 전체는 되는대로

0개의 댓글