(백준/ C++) 2470 - 두 용액📃 coding test/◽ 백준2022. 9. 6. 23:40
Table of Contents
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
'📃 coding test > ◽ 백준' 카테고리의 다른 글
(백준/C++) 가장 긴 증가하는 부분 수열 1(11053), 2(12015), 3(12738), 4(14002), 5(14003) 모두 풀기 (0) | 2023.01.18 |
---|---|
(백준/ C++) 1450 - 냅색문제, 이분 탐색 완전 탐색 그려보자! (0) | 2023.01.12 |
(백준/ C++) 1644 - 소수의 연속 합 (0) | 2022.09.06 |
(백준/ C++) 4673 - 셀프 넘버 (0) | 2022.09.02 |
(백준/ C++) 11066 - 파일합치기 [너무 어려웠던 ..멘탈 탈탈] (0) | 2022.06.29 |
@핑크코냥 :: 핑크코냥
안 하는 것 보다 낫겠지
포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!