문제 링크 : https://www.acmicpc.net/problem/2798

 

2798번: 블랙잭

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

www.acmicpc.net

 

기본적인 완전탐색 문제다.

알고리즘이 너무 오랜만이라 다 까먹어서 처음부터 다시 공부하는 느낌으로 풀었다.

다 풀고나서 다른 사람의 풀이를 보니 재귀함수를 다르게 구현하면 코드가 훨씬 간단해진다는 것을 알고 씁쓸해졌다..

 

소스코드

 

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.ArrayList;
import java.util.Scanner;
 
public class Main {
    
    static int m, answer=0;
    static int[] card;
    static ArrayList<Integer> indexAr = new ArrayList<Integer>();
    
    static public void recur(int n, int toPick) {
        if(toPick==0) {
            compare();
            return;
        }
        int smallest = indexAr.isEmpty() ? 0 : indexAr.get(indexAr.size()-1+ 1;
        
        for(int i= smallest; i<n; i++) {
            indexAr.add(i);
            recur(n, toPick-1);
            indexAr.remove(indexAr.size()-1);
        }
    }
    
    public static void compare() {
        int tot=0, al = indexAr.size();
    
        for(int i=0; i<al; i++) {
            tot += card[indexAr.get(i)];
        }
        if (tot > m) return;
 
        answer = Math.max(answer, tot);
    }
 
    public static void main(String[] args) {
        int n;
        Scanner sc = new Scanner(System.in);
        n = sc.nextInt();
        m = sc.nextInt();
        card = new int[n];
        
        for(int i=0; i<n; i++) {
            card[i] = sc.nextInt();
        }
        
        recur(n, 3);
        System.out.println(answer);
    }
}
cs

 

'Algorithm > 백준' 카테고리의 다른 글

백준 17144번 미세먼지 안녕!  (0) 2019.05.03
백준 16235번 나무재테크  (0) 2019.05.03
백준 15685번 드래곤 커브  (0) 2019.05.02
백준 14891번 톱니바퀴  (0) 2019.04.30
백준 15683번 감시  (0) 2019.04.30

+ Recent posts