๋ฌธ์ :
๋ถ์ :
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;
}
'Algorithm๐ฐ > ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[๋ฐฑ์ค] 2252 ์ค์ธ์ฐ๊ธฐ (0) | 2021.02.14 |
---|---|
[๋ฐฑ์ค] 10828 stack (0) | 2021.02.06 |
[๋ฐฑ์ค] 1915 ๊ฐ์ฅ ํฐ ์ ์ฌ๊ฐํ DP (0) | 2021.02.05 |
[๋ฐฑ์ค] 1987 ์ํ๋ฒณ DFS (0) | 2021.02.05 |
[๋ฐฑ์ค] 2467 ์ฉ์ก ์ด๋ถํ์ (2) | 2021.02.05 |
๋๊ธ