[BOJ] 3273번 운동 - C++

"투 포인터"

Posted by Yongmin on August 3, 2021

문제

두수의 합

풀이

sort를 통해 주어진 수들을 오름차순으로 정렬한 뒤, start = 0, end = testcase.size()-1로 시작하여, 양쪽을 좁혀 나가며 조건에 맞는 것들을 탐색해낸다. 같으면, cont++를 한 뒤, start++, end–를 하고, 합이 x보다 값이 크다면 end– 를 하여 값을 줄여보고, 합이 x보다 값이 작다면 start++를 하여 값을 늘려 탐색해나간다.

소스 코드

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
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    int N;
    scanf("%d", &N);
    
    vector<int> testcase;
    
    for(int i = 0; i<N; i++){
        int input;
        scanf("%d", &input);
        testcase.push_back(input);
    }
    
    int x;
    scanf("%d", &x);
    
    int cont = 0;
    
    sort(testcase.begin(), testcase.end());
    
    int start = 0;
    int end = testcase.size() - 1;
    
    while(start < end){
        if(testcase[start] + testcase[end] == x){
            cont++;
            start++;
            end--;
        }
        else if(testcase[start] + testcase[end] > x){
            end--;
        }
        else if(testcase[start] + testcase[end] < x){
            start++;
        }
    }
    printf("%d\n", cont);
}


# # #