[BaekJoon] 2798번 - 블랙잭 [Java][C++]
[BaekJoon] 2798번 - 블랙잭 [Java][C++]
1. 문제 풀이
세 카드의 합이 $M$ 보다 작으면서 최대가 되는 경우를 찾는 문제로 카드의 수가 최대 $100$ 장이어서 3중 반복문을 활용한 브루트 포스로 해결할 수 있다. 정렬을 활용하면 오름차순으로 카드를 배치할 수 있어서 조기 종료를 할 수도 있다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] arr = new int[N];
st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
int ans = 0;
for (int i = 0; i < N - 2; i++) {
for (int j = i + 1; j < N - 1; j++) {
for (int k = j + 1; k < N; k++) {
int sum = arr[i] + arr[j] + arr[k];
if (sum <= M) {
ans = Math.max(ans, sum);
} else {
break;
}
}
}
}
System.out.println(ans);
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<int> v(n);
for (int& x : v) cin >> x;
sort(v.begin(), v.end());
int ans = 0;
for (int i = 0; i < n - 2; i++) {
for (int j = i + 1; j < n - 1; j++) {
for (int k = j + 1; k < n; k++) {
int sum = v[i] + v[j] + v[k];
if (sum <= m) {
ans = max(ans, sum);
} else {
break;
}
}
}
}
cout << ans;
}
This post is licensed under CC BY 4.0 by the author.