๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 14921๋ฒˆ - ์šฉ์•ก ํ•ฉ์„ฑํ•˜๊ธฐ

by dkswnkk 2021. 11. 14.

๋ฌธ์ œ

 

14921๋ฒˆ: ์šฉ์•ก ํ•ฉ์„ฑํ•˜๊ธฐ

ํ™์ต๋Œ€ ํ™”ํ•™์—ฐ๊ตฌ์†Œ๋Š” ๋‹ค์–‘ํ•œ ์šฉ์•ก์„ ๋ณด์œ ํ•˜๊ณ  ์žˆ๋‹ค.  ๊ฐ ์šฉ์•ก์€ -100,000,000๋ถ€ํ„ฐ 100,000,000์‚ฌ์ด์˜ ํŠน์„ฑ ๊ฐ’์„ ๊ฐ–๋Š”๋ฐ, ๊ฐ™์€ ์–‘์˜ ๋‘ ์šฉ์•ก์„ ํ˜ผํ•ฉํ•˜๋ฉด, ๊ทธ ํŠน์„ฑ๊ฐ’์€ ๋‘ ์šฉ์•ก์˜ ํŠน์„ฑ๊ฐ’์˜ ํ•ฉ์ด ๋œ๋‹ค. ๋‹น

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <vector>
#include <algorithm>
#define INF 2e9+1

using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    int N; cin >> N;
    vector<int>v(N);
    for (int i = 0; i < N; i++) {
        cin >> v[i];
    }
    int start = 0; 
    int end = N - 1;
    int minValue = INF;
    int check,ans;
    while (start < end) {
        check = abs(v[start] + v[end]);
        if (check < minValue) {
            minValue = check;
            ans = v[start] + v[end];
        }
        if (v[start] + v[end] < 0) start++;
        else end--;
    }
    cout << ans;

}

๋Œ“๊ธ€