Post

[백준] 1253번 - 좋다 [Java][C++]

[백준] 1253번 - 좋다 [Java][C++]

문제 링크


1. 문제 풀이

$N$ 개의 수 중에 어떤 수가 다른 두 수의 합으로 나타낼 수 있으면 좋은 수가 되며 좋은 수의 개수를 찾아야 하는 문제다. 이분 탐색이나 투 포인터를 활용하면 해결할 수 있다.

1. 이분 탐색

이분 탐색의 경우 2중 for문과 탐색 구간 분할을 활용하여 해결했다. $i$, $j$, $k$ 가 주어진 수일 때 $i = j + k$ 면 $i$ 는 좋은 수가 된다. 이를 찾기 위해 바깥 for문이 주어진 수들을 탐색하며 안쪽 for문이 $i - j$ 인 $k$ 가 주어진 수 중에 존재하는 지 찾았다. 이때 $i$, $j$, $k$ 가 같은 수(인덱스가 동일)면 안되므로 $i = j$ 면 넘어갔고, $k$ 의 경우 $i, j$ 로 주어진 수를 분할한 세 구간 중에서만 존재하는지 찾았다.

2. 투 포인터

투 포인터의 경우 각 수에 대해 투 포인터로 주어진 수를 만들 수 있는지 찾으면 된다. 이를 위해 for문으로 각 수 $i$ 에 대해 투 포인터를 수행해서 $arr[left] + arr[right] = arr[i]$ 를 만족하는지 찾았다. 투 포인터는 양 끝에서 출발하는 방식으로 찾으면 되며 역시 $left = i, right = i$ 일 때는 넘어가도록 구현했다.


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
36
37
38
39
40
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;

        int N = Integer.parseInt(br.readLine());

        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 cnt = 0;
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                if (i == j) continue;

                // 이분 탐색으로 찾으면 좋은 수
                if (binarySearch(arr, Math.min(i, j), Math.max(i, j), arr[i] - arr[j])) {
                    cnt++;
                    break;
                }
            }
        }

        System.out.println(cnt);
    }

    // 배열을 pivot1, pivot2로 분할한 세 구간 중 key가 존재하는지 리턴
    static boolean binarySearch(int[] arr, int pivot1, int pivot2, int key) {
        return Arrays.binarySearch(arr, 0, pivot1, key) >= 0 ||
                Arrays.binarySearch(arr, pivot1 + 1, pivot2, key) >= 0 ||
                Arrays.binarySearch(arr, pivot2 + 1, arr.length, key) >= 0;
    }
}

2. 투 포인터 [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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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;

        int N = Integer.parseInt(br.readLine());

        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 cnt = 0;
        for (int i = 0; i < N; i++) {
            int left = 0;
            int right = N - 1;

            while (left < right) {
                // 왼쪽 포인터가 i면 넘어감
                if (left == i) {
                    left++;
                    continue;
                }

                // 오른쪽 포인터가 i면 넘어감
                if (right == i) {
                    right--;
                    continue;
                }

                if (arr[left] + arr[right] > arr[i]) {
                    right--;
                } else if (arr[left] + arr[right] < arr[i]) {
                    left++;
                } else {
                    cnt++;
                    break;
                }
            }
        }

        System.out.println(cnt);
    }
}

3. 이분 탐색 [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
31
32
33
34
35
36
#include <bits/stdc++.h>
using namespace std;

// 벡터를 p1, p2로 분할한 세 구간 중 key가 존재하는지 리턴
bool solve(const vector<int>& v, int p1, int p2, int key) {
    return binary_search(v.begin(), v.begin() + p1, key) ||
           binary_search(v.begin() + p1 + 1, v.begin() + p2, key) ||
           binary_search(v.begin() + p2 + 1, v.end(), key);
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;
    sort(v.begin(), v.end());

    int cnt = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j) continue;

            // 이분 탐색으로 찾으면 좋은 수
            if (solve(v, min(i, j), max(i, j), v[i] - v[j])) {
                cnt++;
                break;
            }
        }
    }

    cout << cnt;
}

4. 투 포인터 [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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    vector<int> v(n);
    for (int& x : v) cin >> x;
    sort(v.begin(), v.end());

    int cnt = 0;
    for (int i = 0; i < n; i++) {
        int l = 0;
        int r = n - 1;

        while (l < r) {
            // 왼쪽 포인터가 i면 넘어감
            if (l == i) {
                l++;
                continue;
            }

            // 오른쪽 포인터가 i면 넘어감
            if (r == i) {
                r--;
                continue;
            }

            if (v[l] + v[r] > v[i]) {
                r--;
            } else if (v[l] + v[r] < v[i]) {
                l++;
            } else {
                cnt++;
                break;
            }
        }
    }

    cout << cnt;
}

3. 풀이 정보

1. 이분 탐색 [Java]

언어시간메모리코드 길이
Java 11392 ms14924 KB1312 B

2. 투 포인터 [Java]

언어시간메모리코드 길이
Java 11160 ms14588 KB1317 B

3. 이분 탐색 [C++]

언어시간메모리코드 길이
C++ 17188 ms2024 KB896 B

4. 투 포인터 [C++]

언어시간메모리코드 길이
C++ 1716 ms2020 KB865 B

This post is licensed under CC BY 4.0 by the author.