아카이브
Published 2023. 8. 8. 12:26
2798번: 블랙잭 알고리즘/boj

https://www.acmicpc.net/problem/2798

 

2798번: 블랙잭

첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는 양의 정수이다. 합이 M을 넘지 않는 카드 3장

www.acmicpc.net

풀이

조합을 사용해서 모든 경우의 수를 계산했다.


코드

//java8
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class Main {
    static int num = -1; //M에 가까운 수
    static int calcNum = 0; //계산을 위한 수
    static int N, M;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        int[] cards = new int[N];

        st = new StringTokenizer(br.readLine());
        for (int n = 0; n < N; n++)
            cards[n] = Integer.parseInt(st.nextToken());

        //NC3
        combination(cards, 0, 3);
        System.out.print(num);
    }

    private static void combination(int[] cards, int index, int r) {
        if (r == 0) {
            if (calcNum > M)
                return;
            num = Math.max(calcNum, num);
            return;
        }
        for (int i = index; i < N; i++) {
            calcNum += cards[i];
            combination(cards, i+1, r-1);;
            calcNum -= cards[i];
        }
    }
}

'알고리즘 > boj' 카테고리의 다른 글

1259번: 팰린드롬수  (0) 2023.08.09
15829번: Hashing  (0) 2023.08.09
2292번: 벌집  (0) 2023.08.08
profile

아카이브

@charoon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!