Notice
Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 |
| 9 | 10 | 11 | 12 | 13 | 14 | 15 |
| 16 | 17 | 18 | 19 | 20 | 21 | 22 |
| 23 | 24 | 25 | 26 | 27 | 28 | 29 |
| 30 |
Tags
- directx
- C++
- UnrealEngine4
- winapi
- 줄 세우기
- DirectX11
- softeer
- RootMotion
- RVO
- UnrealEngine5
- C
- TObjectPtr
- const
- 티스토리챌린지
- baekjoon
- 오블완
- NRVO
- 언리얼엔진5
- GeeksForGeeks
- Frustum
- Programmers
- 팰린드롬 만들기
- algorithm
- UE5
- 프로그래머스
- IFileDialog
- 2294
- 백준
- 1563
- Unreal Engine5
Archives
- Today
- Total
Game Develop
[Algorithm]Baekjoon 9024번 :: 두 수의 합 본문
https://www.acmicpc.net/problem/9024
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <math.h>
#include <queue>
#include <functional>
#include <sstream>
#include <memory.h>
#include <deque>
#include <set>
#include <unordered_set>
#include <thread>
#include <atomic>
using namespace std;
int t, n, k;
int arr[1000001] = { 0 };
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> t;
while (t--)
{
cin >> n >> k;
for (int i = 0; i < n; ++i)
{
cin >> arr[i];
}
sort(arr, arr + n);
int left = 0;
int right = n - 1;
int minGap = 0x3f3f3f3f;
int minGapCount = 0;
while (left < right)
{
int num = arr[left] + arr[right];
int gap = abs(k - num);
if (gap == minGap) // 현재까지의 최소갭과 동일하면 카운팅
{
++minGapCount;
}
else if (gap < minGap) // 더 작으면 업데이트.
{
minGap = gap;
minGapCount = 1;
}
if (num <= k)
{
++left;
}
else
{
--right;
}
}
printf("%d\n", minGapCount);
}
}
|
cs |
약간 투포인터문제의 정석 느낌이 나는 문제다.
타겟값k와 가장 가까운 두 수의 합을 구한다음 그 합의 개수까지 구해야 한다.
배열을 정렬 후, 양끝에 두개의 포인터를 둔다음 탐색을 시작할 건데, 값이 오름차순으로 정렬되어 있기 때문에 두 포인터가 가리키는 숫자의 합이 작을경우 값을 늘려야하니까 왼쪽포인터를 한칸 오른쪽으로 옮긴다.
두 숫자의 합이 크면 값을 줄여야하니까 오른쪽포인터를 한칸 왼쪽으로 옮긴다.
매번 옮길때마다 k와의 gap을 업데이트 해주면 되는데 최종출력은 개수를 출력하는 거라서 매 탐색 시 현재까지의 최소gap값과 일치하면 카운팅 해주면 된다. gap값이 더 작은값을 발견하면 다시 초기화해주면 되고.
'Algorithm > Algorithm' 카테고리의 다른 글
| [Algorithm]Baekjoon 1007번 :: 벡터 매칭 (0) | 2025.11.04 |
|---|---|
| [Algorithm]Baekjoon 1461번 :: 도서관 (0) | 2025.09.19 |
| [Algorithm]Baekjoon 17951번 :: 흩날리는 시험지 속에서 내 평점이 느껴진거야 (0) | 2025.09.18 |
| [Algorithm]Baekjoon 3079번 :: 입국심사 (0) | 2025.09.17 |
| LCS (0) | 2023.11.06 |