관리 메뉴

fatalite

☆ 용액 - 백준 2467 본문

코딩 인터뷰/C++

☆ 용액 - 백준 2467

fataliteforu 2023. 4. 11. 05:54

Problem

레벨 : 골드 5

분류 : 이분 탐색, 두 포인터

접근 : 처음에는 완전 탐색 + 중복 없애기로 했음

방법 : 이분 탐색과 포인터 두 개를 움직인다는 게 중요한 아이디어였다.


Solution

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> list;

pair<int, int> combination = { 1000000001,10000000001 };
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(nullptr);
	cout.tie(nullptr);
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		int a; cin >> a;
		list.push_back(a);
	}
	
	int low = 0;
	int high = n - 1;
	combination.first = list[low];
	combination.second = list[high];
	while (high > low) {
		if (abs(list[low] + list[high]) < abs(combination.first + combination.second)) {
			combination.first = list[low];
			combination.second = list[high];
		}
		if (list[low] + list[high] > 0) {
			high--;
		}
			else {
			low++;
		}
	}
	cout << combination.first << " " << combination.second;
}

'코딩 인터뷰 > C++' 카테고리의 다른 글

CCW - 백준 11758번  (0) 2023.07.29
이분 그래프 - 백준 1707  (0) 2023.05.22
☆ 스티커 - 백준 9465  (1) 2023.04.09
트리 순회 - 백준 1991  (0) 2023.04.08
정수삼각형 - 백준 1932  (0) 2023.04.04