문제) 백준 - 이분 탐색 - 합이 0
https://www.acmicpc.net/problem/3151
3151번: 합이 0
Elly는 예상치 못하게 프로그래밍 대회를 준비하는 학생들을 가르칠 위기에 처했다. 대회는 정확히 3명으로 구성된 팀만 참가가 가능하다. 그러나 그녀가 가르칠 학생들에게는 큰 문제가 있었다.
www.acmicpc.net
N이 최대 10000이므로 O(N*N*logN)의 시간 복잡도로 해결할 수 있었습니다. 두 개의 숫자(이중 반복문)를 선택 후, 이분 탐색을 통해 나머지 숫자들 중 0이 되는 숫자의 개수를 세어주면 해결할 수 있습니다.
C++ 소스코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sort(A, A + N); | |
// O(N) | |
for (int i = 0; i < N - 2; ++i) { | |
//O(N) | |
for (int j = i + 1; j < N - 1; ++j) { | |
// O(logN) | |
int total = A[i] + A[j]; | |
ans += (upper_bound(A + j + 1, A + N, (-1) * total) - lower_bound(A + j + 1, A + N, (-1) * total)); | |
} | |
} |
Full Code)
GitHub - Chocochip101/BOJ_Solution: BOJ Solutions
BOJ Solutions. Contribute to Chocochip101/BOJ_Solution development by creating an account on GitHub.
github.com
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 5427번 - 불 (C++) 문제 및 풀이 (0) | 2022.01.24 |
---|---|
[백준] 4358번 - 생태학 (C++) 문제 및 풀이 (0) | 2022.01.23 |
[백준] 19699번 - 소-난다! (Python) 문제 및 풀이 (0) | 2022.01.21 |
[백준] 10546번 - 배부른 마라토너 (C++) 문제 및 풀이 (0) | 2022.01.21 |
[백준] 1072번 - 게임 (C++) 문제 및 풀이 (0) | 2022.01.20 |
댓글