본문 바로가기
알고리즘/백준

백준 2798번 블랙잭 [C++]

by seongjun 2024. 1. 3.

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

 

2798번: 블랙잭

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

www.acmicpc.net

 

 

 

카드 갯수와 특정 숫자, 그리고 카드에 적힌 숫자가 주어질 때, 3개의 카드의 합 중 특정 숫자를 넘지 않으면서 가장 근접한 수를 찾아 출력하면 된다.

 

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;

    int arr[n];
    for (int i=0;i<n;i++){
        cin >> arr[i];
    }

    int answer = 0;
    for (int i=0;i<n-2;i++){
        for (int j=i+1;j<n-1;j++){
            int sum = arr[i] + arr[j];
            for (int k=j+1;k<n;k++){
                if (m >= sum+arr[k]) {
                    if (answer < sum+arr[k]) {
                        answer = sum + arr[k];
                    }
                }
            }
        }
    }
    cout << answer;
}

3중 for문을 통해 모든 경우의 수를 다 탐색하면 쉽게 답을 구할 수 있다.