📃 coding test/◽ 백준

(백준/ C++) 2470 - 두 용액

핑크코냥 2022. 9. 6. 23:40
728x90

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

 

2470번: 두 용액

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

www.acmicpc.net

 

< 문제 키워드 및 풀이 방법 > 

1. 두 수의 합이 0과 가장 가까운 것(음수도 있을 수 있음)을 찾아야 한다.
▶▷ 두 수의 합을 구하고 절댓값으로 비교한다.

2. 주어진 수는 정렬 돼서 주어지지 않는다.
▶▷ 정렬을 후, 투 포인터의 조건을 만들어준다.

※ ex) "백준 1644 - 소수의 연속함" 투 포인터 인덱스 움직임의 조건: sum이 N보다 작으면 twoIdx를 클 때 oneIdx를 증가시킨다.

3. 두 수의 합이므로 인덱스는 서로 같으면 안 된다.
▶▷ while 문의 조건은 while ( point_one < point_two ) 또는 while ( point_one != point_two )

 

< 코드 >

#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>
#include <limits.h>
using namespace std;


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

	int N;
	cin >> N;
	vector<long long> solution;
	
	for (int idx = 0; idx < N; ++idx) {
		long long data; 
		cin >> data; 
		solution.emplace_back(data); 
	}
	sort(solution.begin(), solution.end());
	
	int point_one, point_two, RO, RT; 
	point_one = 0; point_two = solution.size() - 1;
	long long sum = LLONG_MAX;

	while (point_one <point_two)
	{
		if (sum > abs(solution[point_one] + solution[point_two]))
		{
			sum = abs(solution[point_one] + solution[point_two]); 
			RO = solution[point_one];
			RT = solution[point_two];
		}
		
		if (solution[point_one] + solution[point_two] <= 0)
			point_one++;
		else
			point_two--;
	}

	cout << RO << " " << RT;
	return 0; 
	
}

* long long을 int로 바꿔도 된다고 합니다. 

문제 입력 값

 

728x90