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

 

10816번: 숫자 카드 2

첫째 줄에 상근이가 가지고 있는 숫자 카드의 개수 N(1 ≤ N ≤ 500,000)이가 주어진다. 둘째 줄에는 숫자 카드에 적혀있는 정수가 주어진다. 숫자 카드에 적혀있는 수는 -10,000,000보다 크거나 같고, 10,000,000보다 작거나 같다. 셋째 줄에는 M(1 ≤ M ≤ 500,000)이 주어진다. 넷째 줄에는 상근이가 몇 개 가지고 있는 숫자 카드인지 구해야 할 M개의 정수가 주어지며, 이 수는 공백으로 구분되어져 있다. 이수도 -10,00

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
 
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        int[] cards = new int[n];
        
        for(int i = 0; i < n; i++) {
            cards[i] = Integer.parseInt(st.nextToken());
        }
        
        Arrays.sort(cards);
        
        int m = Integer.parseInt(br.readLine());
        
        StringBuffer sb = new StringBuffer();
        st = new StringTokenizer(br.readLine());
        
        for(int i = 0; i < m; i++) {
            int x = Integer.parseInt(st.nextToken());
            int cnt = getCnt(cards, x, n);
            sb.append(cnt + " ");
        }
        
        System.out.println(sb);
    }
 
    private static int getCnt(int[] cards, int x, int n) {
        int left = 0;
        int right = n - 1;
        int cnt = 0;
        
        while(left <= right) {
            int mid = (left + right) / 2;
            
            if(x < cards[mid]) {
                right = mid - 1;
            } else if(x > cards[mid]) {
                left = mid + 1;
            } else {
                cnt = 1;
                int tmp = mid;
                
                while(--tmp >= 0 && cards[tmp] == x) {
                    cnt++;
                }
                
                while(++mid < n && cards[mid] == x) {
                    cnt++;
                }
                
                break;
            }
        }
        
        return cnt;
    }
}
 
 

 

그럼 대체 어떻게 풀어야한단 말인가... 고뇌를 하던 와중, 숫자의 범위가 -10,000,000 ~ 10,000,000이라는 게 눈에 들어왔다. 그럼 20,000,001개의 수이고 int 는 4 byte니까 20,000,001 X 4 = 80,000,004 -> 약 80MB~!!!! 생각보다 배열이 크지 않구만~! 배열에 모든 수의 개수를 저장하면 되겠다는 생각이 들었다. 코드는 아래와 같다.

 

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
 
public class Main {
    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        StringTokenizer st = new StringTokenizer(br.readLine());
        int[] cnt = new int[20_000_001];
        
        for(int i = 0; i < n; i++) {
            cnt[Integer.parseInt(st.nextToken()) + 10_000_000]++;
        }
        
        int m = Integer.parseInt(br.readLine());
        st = new StringTokenizer(br.readLine());
        StringBuffer sb = new StringBuffer();
        
        for(int i = 0; i < m; i++) {
            sb.append(cnt[Integer.parseInt(st.nextToken()) + 10_000_000] + " ");
        }
        
        System.out.println(sb);
    }
}
 
 

 

문제를 만든 사람이 어떤 의도로 만든 문제인지는 모르겠으나, 현재 이 문제는 메모이제이션으로 푸는게 가장 효과적이다. 근데 수의 범위가 더 커진다면, 메모리를 너무 많이 사용해야함으로 이분 탐색이 더 나은 알고리즘이 될지도 모르겠다.

+ Recent posts