๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] 2470 ๋‘์šฉ์•ก ์ด๋ถ„ํƒ์ƒ‰

by Jouureee 2021. 2. 5.

๋ฌธ์ œ : 

www.acmicpc.net/problem/2470

 

2470๋ฒˆ: ๋‘ ์šฉ์•ก

์ฒซ์งธ ์ค„์—๋Š” ์ „์ฒด ์šฉ์•ก์˜ ์ˆ˜ N์ด ์ž…๋ ฅ๋œ๋‹ค. N์€ 2 ์ด์ƒ 100,000 ์ดํ•˜์ด๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ์šฉ์•ก์˜ ํŠน์„ฑ๊ฐ’์„ ๋‚˜ํƒ€๋‚ด๋Š” N๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ๋นˆ์นธ์„ ์‚ฌ์ด์— ๋‘๊ณ  ์ฃผ์–ด์ง„๋‹ค. ์ด ์ˆ˜๋“ค์€ ๋ชจ๋‘ -1,000,000,000 ์ด์ƒ 1,000,00

www.acmicpc.net

๋ถ„์„ : 

algorithm์˜ sort ํ•จ์ˆ˜๋Š” ๊ธฐ๋ณธ sort ํ•จ์ˆ˜์™€ ๋‹ฌ๋ฆฌ ๋งˆ์ง€๋ง‰ ์ธ์ž์— ์‚ฌ์šฉ์ž ์ •์˜ ํ•จ์ˆ˜๋ฅผ ์ถ”๊ฐ€ํ•ด ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๋‹ค. ์œ„ ํ•จ์ˆ˜๋ฅผ ์ด์šฉํ•ด 

1) ๋ฐฐ์—ด์„ ์ ˆ๋Œ€๊ฐ’ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ

2) ์ ˆ๋Œ€๊ฐ’ ๋น„๊ต๋ฅผ ํ†ตํ•ด ์›๋ž˜ ๊ฐ’ ๋ณ€์ˆ˜์— ์ €์žฅ ํ›„ ๋ˆ„์ 

3) ๋งˆ์ง€๋ง‰์œผ๋กœ ์‚ฐ์„ฑ๊ณผ ์•Œ์นผ๋ฆฌ ๊ฐ’ ๊ตฌ๋ถ„ํ•ด swap ํ•˜์—ฌ ์ถœ๋ ฅ

ํ•˜๋Š” ๋ฐฉ์‹์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค.

 

c++ ์ฝ”๋“œ :

//
//  2470_solution1.cpp
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2021/02/05.
//

#include <iostream>
#include <math.h>
#include <algorithm>

using namespace std;

bool compare(int a, int b){
    return abs(a) < abs(b);
}

void solution1(int arr[], int n){
    sort(arr, arr + n, compare);
    
    int initDiff = 2147483647;
    int acid = 0, alkali = 0;
    
    for(int i = 0; i< n - 1; i++){
        int diff = (arr[i] + arr[i+1]) - 0;
        if(abs(diff) < initDiff){
            initDiff = abs(diff);
            acid = arr[i];
            alkali = arr[i+1];
        }
        
    }
    
    if (acid > alkali){
        swap(acid, alkali);
    }
        
    cout << acid << " " << alkali << endl;
}

int main() {
    int n;
    int i=0;
    
    cin >> n;
    int arr[n];
    
    while(i<n){
        cin >> arr[i];
        i++;
    }
    solution1(arr,n);
    return 0;
}

๋Œ“๊ธ€