반응형

https://www.acmicpc.net/problem/2470

 

2470번: 두 용액

첫째 줄에는 전체 용액의 수 N이 입력된다. N은 2 이상 100,000 이하이다. 둘째 줄에는 용액의 특성값을 나타내는 N개의 정수가 빈칸을 사이에 두고 주어진다. 이 수들은 모두 -1,000,000,000 이상 1,000,00

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. 입력받은 수들을 오름차순으로 정렬합니다.

 

2. start를 0, end를 N - 1로 초기화하고, arr[start] + arr[end]의 절댓값이 최소가 될 때 start와 end를 a와 b에 저장합니다.

 

3. arr[start] + arr[end] 의 값이 0보다 크다면 end--, 0보다 작다면 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<algorithm>
#include<cmath>
 
using namespace std;
 
int N;
int arr[100000];
 
int main()
{
    scanf("%d"&N);
 
    for (int i = 0; i < N; i++) {
        scanf("%d"&arr[i]);
    }
 
    sort(arr, arr + N);
 
    int start = 0;
    int end = N - 1;
    int ans = 2000000001;
    int a = 0;
    int b = N - 1;
 
    while (start < end) {
        int temp = arr[start] + arr[end];
        if (ans > abs(temp)) {
            ans = abs(temp);
            a = start;
            b = end;
        }
 
        if (temp > 0) {
            end--;
        }
        else {
            start++;
        }
    }
 
    printf("%d %d", arr[a], arr[b]);
}
cs
반응형

+ Recent posts