알고리즘 문제풀이
[백준/BOJ] 백준 2798번 : 블랙잭
GeniusJo
2020. 9. 16. 21:13
2798번: 블랙잭
첫째 줄에 카드의 개수 N(3 ≤ N ≤ 100)과 M(10 ≤ M ≤ 300,000)이 주어진다. 둘째 줄에는 카드에 쓰여 있는 수가 주어지며, 이 값은 100,000을 넘지 않는다. 합이 M을 넘지 않는 카드 3장을 찾을 수 있�
www.acmicpc.net
카드를 3개 고를 수 있는 경우를 모두 확인해 본다. 중복된 카드 선택을 막기 위해 이전에 고른 카드 다음 카드 중에서 카드를 고른다
코드
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int n, m;
vector<int> card;
int Solve(int last_select, vector<int>& selected)
{
int ret = 0;
//카드3개를 골랐을때
if (selected.size() == 3)
{
int sum = 0;
for (int i = 0; i < selected.size(); i++)
{
sum += selected[i];
}
//합이 m을 넘을때
if (sum > m)
return -1;
return sum;
}
//중복된 카드 선택을 막기위해 이전에 고른 카드 다음 카드중에서 카드를 고른다
for (int i = last_select + 1; i < n; i++)
{
selected.push_back(card[i]);
ret = max(ret,Solve(i, selected));
selected.pop_back();
}
return ret;
}
int main()
{
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int input;
vector<int> selected;
cin >> n >> m;
for (int i = 0; i < n; i++)
{
cin >> input;
card.push_back(input);
}
cout << Solve(-1, selected);
return 0;
}