[BOJ] 2470번 두 용액 - C++

"투 포인터"

Posted by Yongmin on August 3, 2021

문제

두 용액

풀이

sort를 통해 주어진 수들을 오름차순으로 정렬한 뒤, start = 0, end = testcase.size()-1로 시작하여, 양쪽을 좁혀 나가며 조건에 맞는 것들을 탐색해낸다. 0에 가까운 수를 찾는 것이므로, sum이 음수이면, start를 키우고, sum이 양수이면 end를 줄여 0으로 가깝게 만든다.

소스 코드

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
#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);
    }
    
    sort(testcase.begin(), testcase.end());
    
    int diff = 1e15;
    
    int start = 0;
    int end = testcase.size() - 1;
    int result_a = 0;
    int result_b = 0;
    
    while(start < end){
        
        if(abs(diff) > abs(testcase[start] + testcase[end])){
            diff = testcase[start] + testcase[end];
            result_a = testcase[start];
            result_b = testcase[end];
            if(diff == 0)
                break;
        }
            
        if(testcase[start] + testcase[end] < 0){
            start++;
        }
        else{
            end--;
        }
    }
    printf("%d %d\n", result_a, result_b);
    
    
}


# # #