본문 바로가기
Problem Solving/Baekjoon

[백준] 6211 The Eating Puzzle - Backtracking / Java

by graycode 2023. 6. 6.

 문제 링크

 

6211번: The Eating Puzzle

Bessie is on a diet where she can eat no more than C (10 <= C <= 35,000) calories per day. Farmer John is teasing her by putting out B (1 <= B <= 21) buckets of feed, each with some (potentially non-unique) number of calories (range: 1..35,000). Bessie has

www.acmicpc.net

 

 풀이 과정

 

 풀이 코드

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Main {

    static int c;
    static int[] arr;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringTokenizer st = new StringTokenizer(br.readLine());

        c = Integer.parseInt(st.nextToken());
        int b = Integer.parseInt(st.nextToken());

        arr = new int[b];

        st = new StringTokenizer(br.readLine());
        while (b-- > 0)
            arr[b] = Integer.parseInt(st.nextToken());

        bw.write(String.valueOf(recur(0, 0)));
        bw.flush();
    }

    private static int recur(int sum, int idx) {
        if (sum > c)
            return -1;

        if (idx == arr.length)
            return sum;

        return Math.max(recur(sum + arr[idx], idx + 1), recur(sum, idx + 1));
    }

}

댓글