백준 5995 java : DP, 배낭문제

magicdrill·2024년 12월 3일
0

백준 문제풀이

목록 보기
499/654

백준 5995 java : DP, 배낭문제

import java.util.Arrays;
import java.util.Scanner;

public class bj5995 {
    static Scanner scanner = new Scanner(System.in);
    static int [] weight;
    static int H;

    public static void main(String[] args){
        inputData();
        System.out.println(findAnswer());

        scanner.close();
    }

    public static void inputData(){
        System.out.println("\ninputData()");
        int N, i;

        H = scanner.nextInt();
        N = scanner.nextInt();
        weight = new int[N];
        for(i= 0; i < N; i++){
            weight[i] = scanner.nextInt();
        }
    }

    public static int findAnswer(){
        System.out.println("\nfindAnswer()");
        int i, j, N = weight.length;
        int [][] DP = new int[N + 1][H + 1];

        Arrays.fill(DP[0], 0);
        for(i = 1; i <= N; i++){
            for(j = 1; j <= H; j++){
                if(j - weight[i-1] >= 0){
                    DP[i][j] = Math.max(DP[i-1][j - weight[i-1]] + weight[i - 1], DP[i-1][j]);
                }
                else{
                    DP[i][j] = DP[i - 1][j];
                }
            }

            System.out.println(weight[i-1]);
            for(int k = 1; k <= N; k++){
                for(int l = 1; l <= H; l++){
                    System.out.print(DP[k][l] + " ");
                }
                System.out.println();
            }
            System.out.println();
        }

        return DP[N][H];
    }
}

0개의 댓글